This title sounds like a movie!
Here is a "timer demo" : http://jsfiddle.net/wared/uVbb2/.
As you can see, there is a timer set to zero milliseconds. This trick is quite hard to explain but I believe that it deserves a little explanation. As it happens, I would say that without such a timer, when the countdown reaches zero, while
is executed before span.innerHTML = sec + ' sec'
... Yes, indeed, in the opposite way of the reading direction. Consequently, "0 sec" is never displayed since the countdown is erased immediately after, due to span.innerHTML = ''
.
Roughly speaking, the DOM task is queued by default until there’s nothing left for the javascript engine to execute. The "0" timer allows to bypass this default behaviour by shifting the loop to the end of the execution queue, after the DOM task. I know that it can be confusing (and completely off-topic by the way), so, let me suggest you to read this :
Here is the code of the demo :
<button>click to play</button> <span></span>
var tid, span, button;
span = document.getElementsByTagName('span')[0];
button = document.getElementsByTagName('button')[0];
button.onclick = toggle;
function play(sec) {
var i;
span.innerHTML = sec + ' sec';
if (sec) {
tid = setTimeout(function () {
play(--sec);
}, 1000);
} else {
setTimeout(function () {
i = 0;
while (i++ < 5) alert('trapped :P');
toggle();
}, 0);
}
}
function toggle() {
if (tid) {
clearTimeout(tid); // phew...
tid = null;
span.innerHTML = '';
button.style.color = 'black';
button.innerHTML = 'click to play';
} else {
play(5);
button.style.color = 'red';
button.innerHTML = 'DO NOT click me again!';
}
}