zl程序教程

您现在的位置是:首页 >  后端

当前栏目

Node.js 定时器

JSNode 定时器
2023-09-11 14:22:55 时间

官网说明 https://nodejs.org/api/timers.html

The timer module exposes a global API for scheduling functions to be called at some future period of time. Because the timer functions are globals, there is no need to call require(‘timers’) to use the API.

The timer functions within Node.js implement a similar API as the timers API provided by Web Browsers but use a different internal implementation that is built around the Node.js Event Loop.

定时器模块为将来一段时间周期性的函数调用,暴露了一些全局接口。因为定时器函数是全局的,因此它无需调用require(‘timers’)来引入该API。
包括Node.js的定时器函数都实现了一个和Web浏览器相似的API,但是它们有着不同的内部实现,Node.js 中的定时器是建立在事件循环机制下的。

timeout.ref()

When called, requests that the Node.js event loop not exit so long as the Timeout is active. Calling timeout.ref() multiple times will have no effect.

当它被调用了以后,要求只要该定时器处于活动状态,那么Node.js的事件循环就不会退出。如果定时器已被 ref 那么再次调用 ref 不会产生其它影响。

timeout.unref()

When called, the active Timeout object will not require the Node.js event loop to remain active. If there is no other activity keeping the event loop running, the process may exit before the Timeout object’s callback is invoked. Calling timeout.unref() multiple times will have no effect.

当它被调用了以后,存活的超时对象将不需要Node.js事件循环保持活动状态。如果那里没有任何活动来保持时间循环持续运行,那么在超时对象的回调函数被调用之前,进程就将会退出。如果定时器已被 unref,再次调用 unref 不会产生其它影响。
在 setTimeout 的情景中当您 unref 您会创建另一个定时器,并唤醒事件循环。创建太多这种定时器可能会影响事件循环的性能,慎用。

server.on('error', function() {
    try {
        //强制退出机制
        var killTimer = setTimeout(function() {
            process.exit(1);
        }, 3000);
        killTimer.unref();
        server.close(function(){
            //此时所有的连接均已自动关闭,Node.js会自动退出,不需要再调用process.exit(1); 来结束所有进程。如果没有调用unref的话,由于定时器处于活动状态,那么Node.js的事件循环就不会退出。
        });
    } catch(e) {
        console.log('err', e.stack);
    }
});

setImmediate(callback[, …arg])

调度在所有 I/O 事件回调之后、setTimeout 和 setInterval 之前“立即”执行 callback。返回一个可能被 clearImmediate() 用到的 immediateId。可选地,您还能给回调传入参数。

setImmediate(function(){
    console.log('Func exec immediately');
});

setInterval(callback, delay[, …arg])

调度每隔 delay 毫秒执行一次的 callback。返回一个可能被 clearInterval() 用到的 intervalId。可选地,您还能给回调传入参数。
Node.js中的参数和C/C++中的一样,都是传递副本,所以如果这里将编号用参数传递,则修改后的参数在函数结束后其生命周期就会消亡,故只能用全局变量来存储。

var i = 0;
setInterval(function(){
    console.log('Func exec intervally, ' + i);
    i++;
}, 1000);

setTimeout(callback, delay[, …arg])

调度 delay 毫秒后的一次 callback 执行。返回一个可能被 clearTimeout() 用到的 timeoutId。可选地,您还能给回调传入参数。
请务必注意,您的回调有可能不会在准确的 delay 毫秒后被调用。Node.js 不保证回调被触发的精确时间和顺序。回调会在尽可能接近所指定时间上被调用。

function timeoutFunc(name) {
    console.log(name + ' timeout');
}
setTimeout(timeoutFunc, 1000, 'Func');

clearImmediate(immediate)

停止一个 immediate 的触发。

var immediateObj = setImmediate(function() {
    for(var i=0;i<1000;i++) {
        console.log(i);
    }
    console.log('Func exec immediately');
});
clearImmediate(immediateObj);

clearInterval(timeout)

停止一个 interval 的触发。

var intervalObj = setInterval(function(){
    console.log('Func exec intervally');
}, 1000);
clearInterval(intervalObj);

clearTimeout(timeout)

阻止一个 timeout 被触发。

var timeoutObj = setTimeout(function() {
    console.log('timeout');
}, 1000);
clearTimeout(timeoutObj);