如何在进行冗长的 javascript 计算时强制浏览器中的 UI 更新?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6989734/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to force UI updates in the browser while lengthy javascript calculations are in progress?
提问by Chris Farmer
I have one place in a web app where I'm doing a lot of calculations in JavaScript in the browser. They may take from a less than a second to about a minute to run, and I would like to show a progress dialog during this step, but the dialog doesn't show until after my calculations are complete. I started by just trying to show a jquery dialog:
我在 web 应用程序中有一个地方,我在浏览器中用 JavaScript进行大量计算。它们的运行时间可能从不到一秒到大约一分钟不等,我想在此步骤中显示一个进度对话框,但该对话框直到我的计算完成后才会显示。我开始只是尝试显示一个 jquery 对话框:
HTML:
HTML:
<input type="button" id="startwork" value="Start working">
<div id="dialog" title="My dialog">
This should show up immediately on clicking the button.
</div>
Script:
脚本:
$(function() {
$("#startwork").click(function () {
$("#dialog").dialog("open");
// Do some lengthy calculations
for (var i=0; i<1000000000; i++) {
var foo = Math.random();
}
$("#dialog").dialog("close");
alert("done");
});
$("#dialog").dialog({ autoOpen: false });
});
What can I do to force the UI to update prior to the start of the calculations and at defined intervals during the calculations?
我可以做些什么来强制 UI 在计算开始之前以及在计算过程中以定义的时间间隔更新?
回答by Mrchief
Wrap your lengthy calculations inside a setTimeout
:
将您冗长的计算包裹在一个setTimeout
:
setTimeout(function() {
// some length calculations
}, 0);
There should be no more script after setTimeout
.
之后应该没有更多的脚本setTimeout
。
$(function() {
$("#startwork").click(function () {
$("#dialog").dialog("open");
setTimeout(function() {
// some length calculations
for (var i=0; i<1000000000; i++) {
var foo = Math.random();
}
$("#dialog").dialog("close");
alert("done");
}, 0);
});
$("#dialog").dialog({ autoOpen: false });
});
回答by RobG
If you want to show a dialog while calculations are occuring, use setTimeoutto call the long calculations after showing the dialog. If you want to show a progress bar, then you'll have to use a sequence of setTimeoutcalls at convenient points during the processing. When one ends, it updates the progress bar and calls the next one untill everything is done.
如果要在进行计算时显示对话框,请在显示对话框后使用setTimeout调用长计算。如果要显示进度条,则必须在处理过程中的方便点使用一系列setTimeout调用。当一个结束时,它更新进度条并调用下一个,直到一切都完成。
However, while any particular script is running, the UI will be blocked.
但是,当任何特定脚本正在运行时,UI 将被阻止。