检查未决电话 [英] Checking for pending calls
问题描述
我想知道是否有任何方法可以检查某个时刻是否有待执行的未决调用,例如来自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);
一些注意事项:
- 并非所有浏览器都支持
filter
方法 - 如何覆盖全局函数
-
+新日期
有什么作用 - 一个相关问题(只是思考的食物)
- 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屋!