I'm trying to refresh a div from Javascript at each loop and see 1, 2, 3, .... The following code works, but only displays the final result (9998). How is it possible to display all the steps? Thank you in advance.
<html>
<head>
</head>
<body>
<div id="cadre" style="width=100%;height=100%;">
<input type="button" value="Executer" onclick="launch();"/>
<div id="result" ></div>
</div>
<script type="text/javascript">
function launch(){
for (inc=0;inc<9999;inc++){
document.getElementById('result').innerHTML = inc;
}
}
</script>
</body>
</html>
JavaScript execution and page rendering are done in the same execution thread, which means that while your code is executing the browser will not be redrawing the page. (Though even if it was redrawing the page with each iteration of the for loop it would all be so fast that you wouldn't really have time to see the individual numbers.)
What you want to do instead is use the
setTimeout()
orsetInterval()
functions (both methods of thewindow
object). The first allows you to specify a function that will be executed once after a set number of milliseconds; the second allows you to specify a function that will be executed repeatedly at the interval specified. Using these, there will be "spaces" in between your code execution in which the browser will get a chance to redraw the page.So, try this:
Notice that the function
timeoutLoop()
kind of calls itself viasetTimeout()
- this is a very common technique.Both
setTimeout()
andsetInterval()
return an ID that is essentially a reference to the timer that has been set which you can use withclearTimeout()
andclearInterval()
to cancel any queued execution that hasn't happened yet, so another way to implement your function is as follows:Obviously you can vary the
delay
as required. And note that in both cases theinc
variable needs to be defined outside the function being executed by the timer, but thanks to the magic of closures we can define that withinlaunch()
: we don't need global variables.Try