我已经用 setTimeout 函数包装了长时间运行的逻辑 (longLoop),但是在长时间运行的执行结束之前,UI 仍然没有响应。它不允许单击其他 UI 按钮。请查看我下面的示例,如果您发现任何问题,请告诉我。
function longLoop () {
var startLogTime, endLogTime;
startLogTime = new Date().getTime();
console.log("loop begin");
for (var i = 0; i <= 500000000; i++) {
var j = 10;
}
endLogTime = new Date().getTime();
console.log("loop execution takes " + (endLogTime - startLogTime) + " milliseconds");
}
$(document).ready(function () {
$("#btnButton").bind("click", function () {
setTimeout(longLoop, 15);
});
$("#anotherButton").bind("click", function () {
console.log("another operation clicked");
});
});
<input type="button" id="btnButton" value="Start Long Operation" />
<input type ="button" id="anotherButton" value= "Another operation" />
谢谢
最佳答案
即使它是“异步的”,setTimeout
仍然会在主事件循环中调度它的调用。由于主事件循环还接收点击、键盘输入以及网页可能发送的每个事件,您只是在延迟长时间操作卡住 UI 的时间。
如果你想在主事件循环中并行运行你的操作,你应该查看Web workers ,它产生真正的线程(有一些重要的约束)。
关于javascript - SetTimeout 函数仍然使 UI 无响应,直到其操作结束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10607239/