Ian A. Mason wrote:
Consider the simple example:
http://www.w3schools.com/js/tryit.as...js_timing_stop
Note that if you press the start button N times, the counter
increments by 1, N times. So you must press the stop button N
times to stop the incrementing entirely.
The question is what is the semantics here that is responsible
for this stacking, for want of a better word.
There is no 'stacking'. setTimeout() returns a reference (an integer)
that can be used by clearTimeout() to cancel the setTimeout every time
it runs.
In the w3schools example, that reference is stored in the global
variable 't', which is re-set every time setTimeout runs so it always
references the last setTimeout. Since the w3schools example just
increments a counter you can't distinguish which one is actually running
or which one you cancel.
Anyhow, pressing the 'Stop count!' button just clears the last
setTimeout that was called, the others (if there are any) will keep
running. When they next run, they reset t again and you can cancel
another one.
If you have a long interval, you can click 'stop count' several times
and not stop the other timeout because you won't get a reference to it
until it runs again (t referenced the canceled timeout, you have to wait
until it is reset so you can cancel one of the running setTimeouts).
To see it in action, change the line:
document.getElementById('txt').value=c
to
document.getElementById('txt').value=t
and you'll see the value of 't' changing.
--
Rob