我用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" />
Run Code Online (Sandbox Code Playgroud)
谢谢
即使它是"异步"的,setTimeout仍然会在主事件循环上调度它的调用.由于主事件循环还接收点击,键盘输入以及网页可能发送的每个事件,因此您只是推迟长时间操作冻结UI的时刻.
如果要与主事件循环并行运行操作,则应查看Web worker,它会生成实际线程(具有一些重要约束).