如何在进行冗长的 JavaScript 计算时强制更新浏览器中的 UI?
我在网络应用程序中有一个位置,在浏览器中使用 JavaScript 进行大量计算。它们可能需要不到一秒到大约一分钟的时间来运行,我想在此步骤中显示一个进度对话框,但该对话框直到我的计算完成后才会显示。我首先尝试显示一个 jquery 对话框:
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 });
});
我可以做什么来强制 UI 在计算开始之前并按定义的时间间隔进行更新在计算过程中?
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:
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您想在计算发生时显示对话框,请使用 setTimeout 在显示对话框后调用长计算。如果您想显示进度条,则必须在处理过程中的方便点使用一系列 setTimeout 调用。当一个结束时,它会更新进度条并调用下一个,直到一切完成。
但是,当任何特定脚本运行时,UI 将被阻止。
If you want to show a dialog while calculations are occuring, use setTimeout to 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 setTimeout calls at convenient points during the processing. When one ends, it updates the progress bar and calls the next one untill everything is done.
However, while any particular script is running, the UI will be blocked.
将冗长的计算封装在
setTimeout
中:setTimeout
之后不应再有任何脚本。Wrap your lengthy calculations inside a
setTimeout
:There should be no more script after
setTimeout
.