How can I get all timers in javascript?

随声附和 提交于 2020-03-23 02:22:03

问题


I create different timer with setTimeout() function in different class. I want to know if there is a way to get all timeouts together?


回答1:


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();
};

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




回答2:


There's no API to get registered timeouts, but there's a "way" to achieve your goal.

Create a new function, let's call it registerTimeout. Make sure it has the same signature as setTimeout. In this function, keep track of what you need (returned timer id, callback function, timeout period...) and register using setTimeout.

Now you can query your own data structure for registered timeouts.

Of course you should probably keep track of expired / triggered timeouts as well as cleared timeouts...



来源:https://stackoverflow.com/questions/46014061/how-can-i-get-all-timers-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!