JavaScript setTimeout() method

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: 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 (&quot;) when needed: setTimeout( "alert(&quot;Right now I'm learning JavaScript&quot;)", 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.