Timers

setTimeout() and setInterval() allow you to register a function to be invoked once or repeatedly after a specified amount of time has elapsed. These are important global functions of client-side JavaScript, and are therefore defined as methods of Window, but they are general-purpose functions and don’t really have anything to do with the window.

The setTimeout() method of the Window object schedules a function to run after a specified number of milliseconds elapses. setTimeout() returns a value that can be passed to clearTimeout() to cancel the execution of the scheduled function.

setInterval() is like setTimeout() except that the specified function is invoked repeatedly at intervals of the specified number of milliseconds:

setInterval(updateClock, 60000);  // Call updateClock() every 60 seconds

Like setTimeout(), setInterval() returns a value that can be passed to clearInterval() to cancel any future invocations of the scheduled function.

Example 14-1 defines a utility function that waits a specified amount of time, invokes a function repeatedly, and then cancels the invocations after another specified amount of time. It demonstrates setTimeout(), setInterval(), and clearInterval().

Example 14-1. A timer utility function

/*
 * Schedule an invocation or invocations of f() in the future.
 * Wait start milliseconds, then call f() every interval milliseconds, 
 * stopping after a total of start+end milliseconds.
 * If interval is specified but end is omitted, then never stop invoking ...

Get JavaScript: The Definitive Guide, 6th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.