javascript - SetTimeout 函数仍然使 UI 无响应,直到其操作结束

标签 javascript jquery

我已经用 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/

相关文章:

javascript - 有什么办法可以将Javascript中上传的附件文件发送到Python/Flask吗?

javascript - Dojo 扩展 dojo.dnd.Source,移动没有发生。有想法吗?

javascript - JS 平滑滚动,滚动到最终/底部 div 的底部而不是顶部

jquery - 验证复选框组

jquery - : How to highlight certain words with jQuery

带引号的 Javascript 导致 Blogger 模板中缺少参数

javascript - 有没有办法通过 JavaScript 中的 Intl.NumberFormat 反转格式

javascript - 如何阻止 Gmail 最大化 iFrame?

jquery qtip 未在正确的位置显示独特的工具提示

javascript - 滚动到 JavaScript