Skip to content Skip to sidebar Skip to footer

How Can I Get All Timers In Javascript?

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

Solution 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.


Solution 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...


Post a Comment for "How Can I Get All Timers In Javascript?"