在 javascript 排序调用之前强制 element.innerHTML 更新

在 javascript 排序调用之前强制 element.innerHTML 更新

问题描述:

这种情况的最佳实践是什么:1)用户点击排序巨大的javascript数组"2) 浏览器通过 element.innerHTML="Sorting" 显示Sorting..."3) 浏览器在显示排序..."消息的同时对巨大的 javascript 数组(100% CPU 几秒钟)进行排序.4) 浏览器显示结果.

what is the best practice for this scenario: 1) User clicks "Sort huge javascript array" 2) Browser shows "Sorting..." through element.innerHTML="Sorting" 3) Browser sorts huge javascript array (100% CPU for several seconds) while displaying "Sorting..." message. 4) Browser shows result.

伪代码:

...
<a href="#" onclick="sortHugeArray();return false">Sort huge array</a>
...
function sortHugeArray(){
  document.getElementById("progress").innerHTML="Sorting...";
  ...do huge sort ...
  ...render result...
  document.getElementById("progress").innerHTML=result;
}

当我这样做时,浏览器从不显示排序...",它会冻结浏览器几秒钟并显示结果而不通知用户...

When i do that this way, browser never shows "Sorting...", it freezes browser for several seconds and shows result without noticing user...

谢谢你的建议.

您必须将控制权交还给浏览器,让它更新屏幕上的任何更改.使用超时要求它把控制权交还给你.

You have to return control to the browser to let it update any changes on-screen. Use a timeout to ask it to return control to you.

function sortHugeArray(){
    document.getElementById("progress").innerHTML="Sorting...";
    setTimeout(function() {
        ...do huge sort ...
        ...render result...
        document.getElementById("progress").innerHTML=result;
    }, 0);
}

不过,执行脚本几秒钟"有点问题.应该有一种方法可以加快速度,或者将过程分解为多个部分,每隔一段时间返回一次超时控制,以保持页面响应.

It's a bit questionable to be executing a script for ‘several seconds’, though. There should be a way to speed that up, or break the process into parts returning control with a timeout every so often to keep the page responsive.