Force element.innerHTML update before javascript sort call

情到浓时终转凉″ 提交于 2019-12-12 18:28:15

问题


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.

Pseudo code:

...
<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...

Thank you for advice.


回答1:


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.



来源:https://stackoverflow.com/questions/2795517/force-element-innerhtml-update-before-javascript-sort-call

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!