Search code examples
javascripttimeoutsettimeoutsetintervalintervals

How to get interval or timeout by ID


I want to get the data of an interval or a timeout through its ID. Just like document.getElementById('id-of-random-element') will get all the data on that specific element, I want to know if there is any way possible to get the data that was originally set for a timeout or an interval by its ID.

For example:

var a = setInterval(()=>{console.log("abcdef");},1000)
//below is some serious pseudo code
getIntervalById(a) //returns something like (()=>{console.log("abcdef");},1000)

Solution

  • One thing you might consider is to overload timers so you can intercept them and store whatever you might want

    Simple example with setTimeout

    const origTime = window.setTimeout;
    
    setTimeout = function(...args) {
      const id = origTime(...args);
      // do something with arguments and id
      console.log('id:', id, 'delay:', args[1]);
      return id
    }
    
    let id = setTimeout(() => console.log('wtf'), 1000);
    setTimeout(() => console.log('foobar'), 2000)
    
    console.log('external id', id)