检查 JavaScript setTimeout 是否已触发 [英] Checking if a JavaScript setTimeout has fired
问题描述
我希望能够通过 JavaScript 分派大量工作在浏览器中完成,从而使浏览器始终保持响应.
I'd like to be able to dispatch a bunch of work via JavaScript to be done in the browser in such a way that the browser stays responsive throughout.
我尝试采用的方法是将工作分块,将每个块传递给一个函数,然后该函数通过 setTimeout(func, 0)
调用排队.
The approach I'm trying to take is to chunk up the work, passing each chunk to a function that is then queued with a setTimeout(func, 0)
call.
我需要知道所有工作何时完成,因此我将返回的计时器 ID 存储在映射中 (id -> true|false).在我获得计时器 ID 后,此映射在下一个代码块中设置为 false,排队函数在完成时将映射设置为 true...当然,排队函数不知道它的计时器 ID.
I need to know when all the work is done, so I'm storing the returned timer ID in a map (id -> true|false). This mapping is set to false in the next block of code after I have the timer ID, and the queued function sets the mapping to true when it completes... except, of course, the queued function doesn't know its timer ID.
也许有更好/更简单的方法……或者一些关于如何根据需要操纵地图的建议?
Maybe there's a better/easier way... or some advice on how I can manipulate my map as I need to?
推荐答案
我会将工作排在一个数组中,使用一个超时来处理队列并在队列为空时调用回调.类似的东西:
I would queue the work in an array, use one timeout to process the queue and call a callback once the queue is empty. Something like:
var work = [...];
var run = function(work, callback) {
setTimeout(function() {
if(work.length > 0) {
process(work.shift());
setTimeout(arguments.callee, 25);
}
else {
callback();
}
}, 25);
};
run(work, function() {
alert('Work is done!');
});
由于浏览器中的 JavaScript 是单线程的,因此运行多个超时并没有真正的优势(至少我认为这是你正在做的).它甚至可能会降低浏览器的速度.
As JavaScript in browsers is single threaded there is no real advantage to run multiple timeouts (at least I think this is what you are doing). It may even slow down the browser.
这篇关于检查 JavaScript setTimeout 是否已触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!