Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 546
alanforan Avatar asked Oct 29 '25 05:10

alanforan


1 Answers

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

like image 176
Matt Greer Avatar answered Oct 30 '25 23:10

Matt Greer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!