Setting an Alarm with setTimeout()

The built-in JavaScript function setTimeout() tells JavaScript to run a JavaScript command at some time in the future. The function takes two parameters: a JavaScript command and the time (in milliseconds) to wait before running it. For example, the following line causes an alert box to pop up after a visitor has been on a page for three seconds:

setTimeout("alert('You have been on this page for 3 seconds!');", 3000);

The first setTimeout parameter contains the JavaScript statement to execute. This statement must be enclosed by quotes and, like all JavaScript statements, end with a semicolon. Notice that the string to be displayed by the alert command appears between single quotes rather than double quotes (see ...

Get The Book of JavaScript, 2nd 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.