检查未决电话 [英] Checking for pending calls

查看:50
本文介绍了检查未决电话的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有任何方法可以检查某个时刻是否有待执行的未决调用,例如来自AJAX请求的回调或计时器( setTimeout ).

I'm wondering if there is any way to check if there are any pending calls that'll be executed at some point, like for example a callback from an AJAX request or a timer (setTimeout).

类似于检查正在运行JavaScript的引擎的整个堆栈.

Something like checking the entire stack of the engine that is running JavaScript.

推荐答案

考虑到AJAX回调依赖于服务器响应(成功,失败),您无法定义它们是否在等待被调用,直到实际时间给他们打电话.

Considering that AJAX callbacks are dependent on the server response(success, failure), you can't define if they are pending to be called, until it's actually time to call them.

但是这是一个想法,如何针对 setTimeout (可能还有 setInterval )实现此检查:

But here's an idea how this checking can be achieved for setTimeout (and maybe setInterval):

window.timeoutsRegistry = [];

window.oldSetTimeout = window.setTimeout;

window.setTimeout = function(func, delay) {
    var tId = window.oldSetTimeout(function() {
        try {
            func();
        }
        catch (exception) {
            //Do Error Handling
        }
    }, delay);

    var startedAt = (+new Date);

    window.timeoutsRegistry[tId] = {
        id: tId,
        callback: func,
        delay: delay,
        startedAt: startedAt,
        isPending: function () {
            var now = (+new Date);

            return ((startedAt + delay) > now);
        }
    };
};

for(var i =0; i < 10; i++) {
    setTimeout(function() {
        1+1;
    }, 200000);
}


console.log(window.timeoutsRegistry);

var pending = window.timeoutsRegistry.filter(function(element) {
    return element.isPending();
});

console.log(pending);

一些注意事项:

  • the filter method is not supported in all browsers
  • How to override a global function
  • What does +new Date do
  • A related question (just food for thought)

这篇关于检查未决电话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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