- The setTimeout() method creates a one-time countdown timer (unlike the setInterval() method, which is used for perpetual / recurring timers). You pass two arguments to setTimeout() - the JavaScript code whose execution you want to delay, and second, a timer measured in milliseconds:
setTimeout( "alert('Hello!')", 1000 ); // Display message after 1 second
Tip: 1 second = 1,000 milliseconds → convert milliseconds to seconds, minutes, and hours.
- Specify the code to run as a quoted string, with function name and optionally arguments:
setTimeout( "stuffToDo()", 999 ); // Argument-less function
setTimeout( "stuffToDo(23,'John Doe',5.75)", 999 ); // Function w/ arguments
Tip: if you run out of single and double-quotes, you can also escape them by putting a backslash character in front of the nested quotes. Here's a timeout that uses inner double-quotes: setTimeout( "alert( 'My name is John \"incognito\" Doe' )" , 123 );
- To execute a single function without argument, save a few bytes with this shortcut notation:
setTimeout( stuffToDo, 999 ); // no quotes or parentheses needed!
- You can have multiple timeouts per page, a good way to make web pages responsive faster by postponing secondary functionality. Timers only start when the code containing them is executed.
- When you pass JavaScript code that contains strings, make sure to escape double-quotes and single-quotes with backslashes. Use HTML entity quotes (") when needed:
setTimeout( "alert("Right now I'm learning JavaScript")", 999 );
- Trick: use setTimeout() to automatically focus inside text fields; if the form field isn't fully loaded, the blinking insertion point won't set itself. Only a short delay is necessary:
// Wait about 0.1 second:
setTimeout( "document.getElementById('firstName').focus()", 99 );
Note: if the field contains a pre-filled, default value, you can use "select()" instead of "focus()".
- The timer expires when: • It reaches the end of its countdown, and the action fires.
• You manually stop it with the clearTimeout() method (cancels timers).
• The user navigates to a different page, or closes the web browser window.
Sister methods:
• setTimeout() starts a single countdown timer, cancellable by clearTimeout() before it expires.
• setInterval() launches a series of recurring timers that run until stopped with clearInterval().