Javascript - 如何在繁重的工作中避免阻止浏览器? [英] Javascript - how to avoid blocking the browser while doing heavy work?
问题描述
我的JS脚本中有这样的功能:
I have such a function in my JS script:
function heavyWork(){
for (i=0; i<300; i++){
doSomethingHeavy(i);
}
}
也许doSomethingHeavy本身就可以,但是重复一遍300次导致浏览器窗口卡住不可忽略的时间。在Chrome中,这不是一个大问题,因为只有一个Tab受到影响;但对于Firefox来说这是一场彻底的灾难。
Maybe "doSomethingHeavy" is ok by itself, but repeating it 300 times causes the browser window to be stuck for a non-negligible time. In Chrome it's not that big of a problem because only one Tab is effected; but for Firefox its a complete disaster.
有没有办法告诉浏览器/ JS放轻松而不是阻止对doSomethingHeavy的调用之间的所有内容?
Is there any way to tell the browser/JS to "take it easy" and not block everything between calls to doSomethingHeavy?
推荐答案
您可以在 setTimeout
电话中嵌套您的电话:
You could nest your calls inside a setTimeout
call:
for(...) {
setTimeout(function(i) {
return function() { doSomethingHeavy(i); }
}(i), 0);
}
将此呼叫排队到 doSomethingHeavy
用于立即执行,但其他JavaScript操作可以嵌入它们之间。
This queues up calls to doSomethingHeavy
for immediate execution, but other JavaScript operations can be wedged in between them.
更好的解决方案是让浏览器实际通过以下方式生成新的非阻塞进程 Web Workers ,但这是HTML5特有的。
A better solution is to actually have the browser spawn a new non-blocking process via Web Workers, but that's HTML5-specific.
编辑:
使用 setTimeout(fn,0 )
实际上花费的时间比零毫秒长 - 例如,Firefox,强制执行至少4毫秒的等待时间。更好的方法可能是使用 setZeroTimeout ,它更喜欢 postMessage
用于即时,可中断的函数调用,但使用 setTimeout
作为旧版浏览器的后备。
Using setTimeout(fn, 0)
actually takes much longer than zero milliseconds -- Firefox, for example, enforces a minimum 4-millisecond wait time. A better approach might be to use setZeroTimeout, which prefers postMessage
for instantaneous, interrupt-able function invocation, but use setTimeout
as a fallback for older browsers.
这篇关于Javascript - 如何在繁重的工作中避免阻止浏览器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!