Get function associated with setTimeout or setInterval

前端 未结 4 1153
难免孤独
难免孤独 2021-01-13 23:46

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, as

4条回答
  •  清歌不尽
    2021-01-14 00:19

    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.

提交回复
热议问题