Next page | Contents page |

Timers - setTimeout, setInterval, requestAnimationFrame

Timer functions seem to confuse beginners because they wonder whether they are meant to make the program wait, or sleep for a while. No, the fundamental process happens as on the previous page.

The purpose of calling the functions setTimeout or setInterval is to tell the system to start a function at some future time (a timer event will occur):

  setTimeout (f, 100);
will cause a new process to start after 100 milliseconds (0.1 seconds) by invoking function f. As usual, f runs to its end and that is the end of the process.

Slightly differently,

  setInterval (f, 100);
will repeatedly fire timer events at intervals of the specified number of milliseconds: useful if you want to keep a clock running on the screen, for example, as we did way back in Part 1.

Another function, similar in some ways, is requestAnimationFrame. This attempts to update the display on the next frame as determined by the display hardware. This typically happens 60 times per second (every 16.67ms). For more details see Mozilla's reference page.

These functions are useful in making games, particularly if you want to do some animation.

Diagram showing how the interface between user and program

All 3 functions (setTimeout, setInterval and requestAnimationFrame) return an identifier for the system object responsible for firing the event. It is possible to use the identifier to cancel the timer. This may become necessary if your code cannot complete within the required time interval. If that happens you could have a queue of potential events building up and your program could become unresponsive: it cannot handle a user event until it has dealt with the others in the queue. My way of dealing with this is to push each timer identifier onto an array. Each time the process is triggered I then check whether there is more than one timer identifier in the array and, if so, cancel and remove from the array all but the last one.

Next page | Contents page |