Node.js – timeout-ref() & timeout-unref() 方法


Timeout 对象是内部创建的,并由 setTimeout()setInterval() 方法返回。如果要取消计划的操作,可以使用此对象并将其传递给 clearTimeout() 或 clearInterval()。

以下是可用于控制默认行为的 timeout 类 ref 对象

1. timeout.ref()

如果 timeout 对象的事件循环不存在,则调用此方法。此方法的实际用途仅在调用 timeout.unref() 后,并且需要再次引用 timeout 对象时。

语法

timeout.ref()

2. timeout.unref()

此方法将告诉 timeout 对象 Node.js 事件循环不再需要处于活动状态。如果没有其他活动或正在运行的进程,则在调用 Timeout 对象的回调之前,进程可能会退出。

语法

timeout.unref()

示例

创建一个名为“timeout.js”的文件并复制以下代码。创建文件后,使用命令“node timeout.js”运行此代码,如下例所示。

// Timeout class Demo Example

// Setting the Timeout using setTimeout() Method
var Timeout = setTimeout(function fun() {
   console.log("1. Setting Timeout for 100ms", 100);
});

// Checking if the timeout.hasRef() object
console.log("2. ", Timeout.hasRef();

// Printing the Timeout ref
console.log("3. ", Timeout.ref());

// Unreferencing and referencing again
console.log("4. ", Timeout.unref());

// Checking if the reference is removed ?
console.log("5. ", Timeout.hasRef());

Timeout.ref()

// Refreshing the timer
console.log("6. ", Timeout.hasRef());

// Clears setInterval Timeout
clearTimeout(Timeout);

console.log("7. Timeout is cleared !");

输出

它将产生以下输出:

2. true
3. Timeout {
   _called: false,
   _idleTimeout: 1,
   _idlePrev: [TimersList],
   _idleNext: [TimersList],
   _idleStart: 358,
   _onTimeout: [Function: fun],
   _timerArgs: undefined,
   _repeat: null,
   _destroyed: false,
   [Symbol(unrefed)]: false,
   [Symbol(asyncId)]: 5,
   [Symbol(triggerId)]: 1 }
4. Timeout {
   _called: false,
   _idleTimeout: 1,
   _idlePrev: null,
   _idleNext: null,
   _idleStart: 358,
   _onTimeout: [Function: fun],
   _timerArgs: undefined,
   _repeat: null,
   _destroyed: false,
   _handle: [Timer],
   [Symbol(unrefed)]: false,
   [Symbol(asyncId)]: 5,
   [Symbol(triggerId)]: 1 }
5. false
6. true
7. Timeout is cleared !

更新于:2021年11月24日

830 次查看

开启你的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.