且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在javascript中获取所有计时器?

更新时间:2023-11-17 16:39:52

默认情况下没有,没有.您可以制作自己的模块,让您跟踪计时器,并为您提供列表.大致:

Not by default, no. You could make your own module that lets you keep track of the timers, and which gives you the list. Roughly:

// ES2015+ version
const activeTimers = [];
exports.setTimeout = (callback, interval, ...timerArgs) => {
    const handle = setTimeout((...args) => {
        const index = activeTimers.indexOf(handle);
        if (index >= 0) {
            activeTimers.splice(index, 1);
        }
        callback(...args);
    }, interval, ...timerArgs);
    activeTimers.push(handle);
};
exports.getActiveTimers = () => {
    return activeTimers.slice();
};

...然后使用它的 setTimeout 而不是全局的.

...then use its setTimeout instead of the global one.