4

假设我有从setTimeoutor返回的超时 ID setInterval

我能以某种方式获得与之相关的原始函数或代码吗?

像这样的东西:

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

var fn = timer_id.get_function(); // desired method
fn(); // output: 'Hello Stackoverflowers!'
4

4 回答 4

4

你可以放一个包装setTimeout- 我只是把这个放在一起(经过几次测试迭代......)

(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];
     }
})();

注意:如果您使用字符串作为回调,这将不起作用。但是没有人这样做,他们..?

它也不支持将 ES5 附加参数传递给回调函数,尽管这很容易支持。

于 2013-05-02T13:39:21.577 回答
2
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
于 2013-05-02T13:36:34.323 回答
1

您可以将每个超时函数存储在一个对象中,以便以后检索它。

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];
    }
}
于 2013-05-02T13:33:31.320 回答
0

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
于 2013-05-02T13:24:23.670 回答