如何中断 javascript 以刷新事件

How to interupt javascript to flush events

本文关键字:javascript 刷新 事件 中断 何中断      更新时间:2023-09-26

我有一个在文档加载上运行的函数,它将选择对象的内容复制到其他选择框(以节省网络带宽)。

该函数需要几秒钟才能完成,因此我想屏蔽主div(让用户知道正在发生某些事情)。

不幸的是,掩码直到函数完成后才会显示:

    // I want the mask to show immediately here, but never gets shown
    $('#unassignedPunchResults').mask('Getting results');
    $('.employeeList').each(function (i) {
        // this is freezing the browser for a few seconds, the masking is not showing
        $('#employeeList option').clone().appendTo(this);  
    });
    $('#unassignedPunchResults').unmask();

如何在 mask() 调用后中断 javascript 以刷新该事件并继续,以便用户可以在较长的处理(each())进程时看到掩码?

将其余代码放在setTimeout(function() { ... }, 0)调用中。

我已经考虑了一段时间。第一种解决方案是使用 settimeout 函数。

但是,它可能有点"脏",因为您添加了任意延迟。更合适的逻辑是在掩码函数执行并呈现 benne 之后执行 $('.employeeList').each(function (i)... 函数。

Jquery 允许我们使用延迟函数来做到这一点,例如在满足延迟条件后进行 xecutes。

所以试试:

// I want the mask to show immediately here, but never gets shown
    $('#unassignedPunchResults').mask('Getting results').then(function(){
    $('.employeeList').each(function (i) {
        // this is freezing the browser for a few seconds, the masking is not showing
        $('#employeeList option').clone().appendTo(this);  
    });

});

通常,使用任意毫秒数的 settimeout 是一种适用于简单情况的解决方案,但如果在复杂代码中有多个 settimout,那么您可能会遇到同步问题。

或使用工作器,但随后您需要丢弃 msie <10或者将计算分解为运行时间少于 500 毫秒的段,并使用 setInterval 将加载记录在 5 秒以上。Google 在 JavaScript 中模拟线程以获取代码示例。