我想知道是否有任何方法可以检查是否有任何将在某个时刻执行的未决调用,例如来自 AJAX 请求或计时器的回调 (setTimeout
).
类似于检查运行 JavaScript 的引擎的整个堆栈。
最佳答案
考虑到 AJAX 回调依赖于服务器响应(成功、失败),您无法定义它们是否等待调用,直到实际调用它们的时间。
但是这里有一个关于如何为 setTimeout
(可能还有 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);
一些注意事项:
关于javascript - 检查未决调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13604365/