Search code examples
javascriptdom-events

How can I update the DOM while running intense JavaScript?


I'm writing JavaScript which is counting up to a certain number for a project. The number could be around 100,000 and It will take roughly 10-15 seconds to complete processing. I want the script to run as soon as the user calls the page and when the script completes it does a redirect. Is it possible to pause for even 10ms to update the DOM while it is running to give feedback such as "Still working"?

I would like to avoid the use of jQuery and web-workers are not an option in this situation. I realise this isn't a real world application!

EDIT: Added some of the code as a sample:

In the head:

function myCounter (target) {
    var t = target;
    var count = 0;
    while (t != count){
        if (t == count) {
        window.location.replace("http://example.com"); // redirect
        }
    count++;
    }
}

In the body:

<script>myCounter(100000);</script>

Solution

  • In most browsers JavaScript and the UI run in the same thread. You can give the thread back to the browser by using setTimeout (or setInterval).

    var myNumber = 0;
    updateNumber();
    
    function updateNumber(){
        // do heavy work for great good, ideally divided into smaller chunks
    
        document.getElementById('updateDiv').innerHTML = 'still working, up to ' + myNumber;
    
        if(myNumber < limit) {
          setTimeout(updateNumber, 20);
        }
    }
    

    For a lot more details on the general process, this answer is worth a read: https://stackoverflow.com/a/4575011/194940