Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get function associated with setTimeout or setInterval

Let's assume that I have the timeout ID returned from setTimeout or setInterval.

Can I get, in some way, the original function or code, associated with it?

Something like this:

var timer_id = setTimeout(function() {
    console.log('Hello Stackoverflowers!');
}, 100000);

var fn = timer_id.get_function(); // desired method
fn(); // output: 'Hello Stackoverflowers!'
like image 768
franzlorenzon Avatar asked Mar 24 '23 02:03

franzlorenzon


1 Answers

You can put a wrapper around setTimeout - I just threw this one together (after a few iterations of testing...)

(function() {
     var cache = {};

     var _setTimeout = window.setTimeout;
     var _clearTimeout = window.clearTimeout;

     window.setTimeout = function(fn, delay) {
         var id = _setTimeout(function() {
             delete cache[id];  // ensure the map is cleared up on completion
             fn();
         }, delay);
         cache[id] = fn;
         return id;
     }

     window.clearTimeout = function(id) {
         delete cache[id];
         _clearTimeout(id);
     }

     window.getTimeout = function(id) {
         return cache[id];
     }
})();

NB: this won't work if you use a string for the callback. But no one does that, do they..?

Nor does it support passing the ES5 additional parameters to the callback function, although this would be easy to support.

like image 85
Alnitak Avatar answered Apr 01 '23 15:04

Alnitak