JavaScript Semantics Question (setTimeout)

R

RobG

Ian said:
Consider the simple example:

http://www.w3schools.com/js/tryit.asp?filename=tryjs_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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,902
Latest member
Elena68X5

Latest Threads

Top