The code below periodically updates a div element with new text. If I set a breakpoint in the Chrome debugger and run in step mode the code updates the html as I expected. But if run without any breakpoint set I see:
minutes = 0 seconds = 0
printed and then no change.
What am I doing wrong?
<html>
<script type="text/javascript">
var g_t1 = null;
var g_t2 = null;
function StartTimer() {
g_t1 = new Date();
}
function StopTimer() {
g_t2 = new Date();
}
function CalcDuration() {
StopTimer();
var diff = g_t2.getTime() - g_t1.getTime();
var place = document.getElementById("here");
var minutes = Math.floor((diff / 1000) / 60);
var seconds = Math.floor((diff / 1000) % 60);
place.innerHTML = "minutes = " + minutes + " seconds = " + seconds;
window.setTimeout(CalcDuration(), 100);
}
function Poller() {
if(!g_t1)
StartTimer();
window.setTimeout(CalcDuration(), 100);
}
</script>
<body onload="Poller();">
<div id="here"></div>
</body>
</html>
EDIT.
For anyone interested both these variants work:
window.setTimeout(CalcDuration, 100);
or
window.setTimeout(function(){CalcDuration()}, 100);
You need to wrap your timer function call in an anonymous function, otherwise it executes immediately instead of within the scope of the timer.