5

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

4
  • You cannot do that. The setTimeout() and setInterval() functions return values, but you have to keep track of them with your own code.
    – Pointy
    Sep 2, 2017 at 13:01
  • How about using a static implementation of setTimeOut()? THis can be called from all classes and also calls can be tracked. Sep 2, 2017 at 13:03
  • You have to store return id somewhere in common array then you can check that
    – Yogesh
    Sep 2, 2017 at 13:03
  • You may find the answers and packages mentioned here useful: stackoverflow.com/q/26057328/3412775
    – Tomty
    Nov 30, 2020 at 15:44

2 Answers 2

4

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.

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.