unref在nodejs timer中的作用


unref()是nodejs中Timeout对象的一个函数,但是解释的不太容易懂,通过代码示例就容易多了。

保存下面代码成一个js文件,node运行。如果注释掉unref一行代码,will i run?打印出来以后程序才退出。如果使用unref,那么程序打印完last line就直接退出了。

就酱。

const timerObj = setTimeout(() => {
console.log(‘will i run?’);
}, 8000);

// if left alone, this statement will keep the above
// timeout from running, since the timeout will be the only
// thing keeping the program from exiting
//timerObj.unref();

console.log(“last line”)

 

 


发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注