获取与 setTimeout 或 setInterval 关联的函数 [英] Get function associated with setTimeout or setInterval

查看:60
本文介绍了获取与 setTimeout 或 setInterval 关联的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有从 setTimeoutsetInterval 返回的超时 ID.

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?

像这样:

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

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

推荐答案

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

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..?

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

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

这篇关于获取与 setTimeout 或 setInterval 关联的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆