The setTimeout() method is a timing event where a set of code is executed after a specified number of milliseconds.

The setTimeout() does not stops the execution of script till the expected time is elapsed. It meagerly sends the timer and associated task to the background and is resumed after the time is elapsed. The setTimeout() is timing event defined in  HTML DOM Window object.

Syntax for setTimeout()

var mytime = window.setTimeout(“javascriptFunction”, “time in milliseconds”);

The setTimeout method can be cleared (stopped) by using clearTimeout() method.

Syntax for clearTimeout()

window.clearTimeout(mytime);

Advantage of using setTimeout()

The setTimeout() method is useful when it has to be executed after some specified time and not when it is called.

Disadventage of using setTimeout()

The setTimeout() method associated with the setTimeout() is called when the time elapsed. But if there is another execution going on, the delay associated with calling the setTimeout() function is longer than specified value and unwanted.

The example below sets the timer for filling the form value. After the time od 3 seconds is expired, the background color of the form turns red and alert appears saying "time out for filling form" occurs.

Example with setTimeout() based repeating timer

 

›› go to examples ››