4

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>
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
alanforan
  • 43
  • 4

1 Answers1

4

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

Community
  • 1
  • 1
Matt Greer
  • 60,826
  • 17
  • 123
  • 123
  • I find it best to time the "do work" to limit time (say 50ms) and then yield for some time (say 30ms). The timings will vary by browser/environment, but a 0ms (really about 5ms-15ms in imp.) timeout makes things *really choppy* in some browsers. –  Feb 28 '13 at 03:02
  • @pst yeah, that is probably true. I changed it to 20 milliseconds. – Matt Greer Feb 28 '13 at 03:03
  • "In most browsers JavaScript and the UI run in the same thread" Now you've got me curious, which browsers don't the UI and JS run in the same thread? – greim Feb 28 '13 at 03:46
  • That's what I've actually been trying to do but I can't get it to work. I added a sample of the way my code is formatted above! Thanks for your help – alanforan Feb 28 '13 at 10:35
  • Ah, I figured it out! Thanks :) – alanforan Feb 28 '13 at 11:46