Is there a way to make JavaScript print a counter continuously in the same place on the page?
for(var x=0; x<3000; x++){
document.write(x + '</br>');
document.body.innerHTML = "";
}
I want the number x to update and replace the previous number, however this code seems to wait until the loop is finished before showing a number (by then it is too late)
Is there a way to say, print number x, now wait 100ms, now clear and update in the same space the new value for x, and repeat?
(I know that the innerHTML is killing the whole page, for now all this pages needs to do is run a counter, so other elements are irrelevant. What I don’t want is a printed list of all those numbers, and I need a delay)
Thanks!
The browser will not update the display while JavaScript is running. To make a timer happen you need to use
setTimeout()orsetInterval(). Also, avoiddocument.write()unless you have a good reason to use it (if you’re not sure what makes a good reason then don’t use it at all).You want something like this:
Then:
Demo: http://jsfiddle.net/nnnnnn/v5hmE/
Note that the above updates only the contents of the “counter” div, so any other elements on your page would not be affected.
Homework assignment for you: Google everything you didn’t understand in that code.