Updating element.innerHTML element before calling javascript sort
What is the best practice for this scenario: 1) User clicks "Sort huge javascript array" 2) Browser shows "Sort ..." via element.innerHTML = "Sort" 3) Browser sorts huge javascript array (100% cpu within a few seconds ) when the message "Sorting ..." is displayed. 4) The browser shows the result.
Pseudocode:
...
<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 this, the browser never shows "Sort ...", it freezes the browser for a few seconds and shows the result without noticing the user ...
Thanks for the advice.
a source to share
You must return control to the browser for it to update any changes on the screen. Use the timeout to ask him to take back control.
function sortHugeArray(){
document.getElementById("progress").innerHTML="Sorting...";
setTimeout(function() {
...do huge sort ...
...render result...
document.getElementById("progress").innerHTML=result;
}, 0);
}
This is a bit dubious if you are executing the script in a few seconds. There must be a way to speed this up, or to break the process into chunks that time out return as often as possible to keep the page responsive.
a source to share