如何判断setInterval是否是阻止应用退出的最后一件事

How to tell if a setInterval is the last thing that's stopping an app from exiting

本文关键字:退出 最后 一件 应用 何判断 判断 setInterval 是否是      更新时间:2023-09-26

是否有一种方法可以知道在进程自动退出之前节点必须完成多少任务,因为没有其他事情可做?我想使用setInterval,但只有在应用程序繁忙的时候。我不想阻止进程自动触发退出事件:

// an app that does serveral things, then finishes
// this should only be active whilst the app is busy:
var interval = setInterval(function(){
    // some stuff
    // how to determine if the interval is the last thing to complete?
    if(process.lastThingToDo == interval)
        clearInterval(interval);
}, 2500);

如果您想使用一个定时器,它仍然会像普通定时器一样工作,但不会阻止进程退出,您可以在它上使用.unref()

// an app that does serveral things, then finishes
// this should only be active whilst the app is busy:
var interval = setInterval(function(){
    // some stuff
    // how to determine if the interval is the last thing to complete?
    if(process.lastThingToDo == interval)
        clearInterval(interval);
}, 2500);
// add this .unref() call to make it so the process will not wait for this timer
// before exiting, but the timer will otherwise work normally
interval.unref();

查看node.js文档中.unref()的定时器