防止长时间运行的javascript锁定浏览器 [英] Prevent long running javascript from locking up browser
问题描述
我有JavaScript执行大量计算以及从DOM读取/写入值。页面很大,所以这通常会导致浏览器长达一分钟(有时更长时间使用IE),CPU占用率为100%。
I have JavaScript which performs a whole lot of calculations as well as reading/writing values from/to the DOM. The page is huge so this often ends up locking the browser for up to a minute (sometimes longer with IE) with 100% CPU usage.
是否有任何优化资源用来防止这种情况发生的JavaScript(我能找到的就是如何关闭Firefox长时间运行的脚本警告)?
Are there any resources on optimising JavaScript to prevent this from happening (all I can find is how to turn off Firefox's long running script warning)?
推荐答案
如果你可以将您的计算算法转换为可以迭代调用的内容,您可以使用 setTimeout 。
if you can turn your calculation algorithm into something which can be called iteratively, you could release control back the browser at frequent intervals by using setTimeout with a short timeout value.
例如,类似这样的东西......
For example, something like this...
function doCalculation()
{
//do your thing for a short time
//figure out how complete you are
var percent_complete=....
return percent_complete;
}
function pump()
{
var percent_complete=doCalculation();
//maybe update a progress meter here!
//carry on pumping?
if (percent_complete<100)
{
setTimeout(pump, 50);
}
}
//start the calculation
pump();
这篇关于防止长时间运行的javascript锁定浏览器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!