Get function associated with setTimeout or setInterval

为君一笑 提交于 2019-12-01 06:18:30
Alnitak

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.

epascarello
var timeouts = {};  // hold the data
function makeTimeout (func, interval) {

    var run = function(){
        timeouts[id] = undefined;
        func();
    }

    var id = window.setTimeout(run, interval);
    timeouts[id] = func;

    return id;
}
function removeTimeout (id) {
    window.clearTimeout(id);
    timeouts[id]=undefined;
}
function doTimeoutEarly (id) {
  func = timeouts[id];
  removeTimeout(id);
  func();
}

var theId = makeTimeout( function(){ alert("here"); }, 10000);
console.log((timeouts[theId] || "").toString());
timeouts[theId](); // run function immediately, will still run with timer

You can store each timeout function in an object so that you can retrieve it later.

var timeout_funcs = {};

function addTimeout(func,time) {
    var id = window.setTimeout(func,time);
    timeout_funcs[id] = func;
    return id;
}

function getTimeout(id) {
    if(timeout_funcs[id])
        return timeout_funcs[id];
    else
        return null;
}

function delTimeout(id) {
    if(timeout_funcs[id]) {
        window.clearTimeout(timeout_funcs[id]);
        delete timeout_funcs[id];
    }
}
jbabey

the IDs returned from setTimeout/setInterval are just numbers, they have no properties or methods other than those that every other number would have. If you want to get that function, you can declare it first instead of using an anonymous:

var myFunc = function() {
    console.log('Hello Stackoverflowers!');
};

var timer_id = setTimeout(myFunc, 100000);

myFunc(); // output: 'Hello Stackoverflowers!'

clearTimeout(timer_id); // unless you want it to fire twice
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!