SetTimeout and setInterval: Delays in JavaScript

JavaScript can trigger action after an interval of time, or repeat it after an interval of time.

SetTimeout and setInterval methods are methods of the window object. We can then write setTimeout or window.setTimeout.
These are independent processes that, when they are initiated by an instruction, do not block the display of the rest of the page or the actions of the user.

SetTimeout indicates a delay before execution

The setTimeout method defines an action to perform and a delay before its execution. It returns an identifier for the process.

var x = setTimeout ("instructions" delay in milliseconds).


function myfonction() { ...

setTimeout(myfonction, 5000); 

The function will be executed after 5 seconds (5000 milliseconds).

The delay begins at the moment where setTimeout is executed by the JavaScript interpreter, so from the loading of the page if the instruction is in a script executed at load, or from a user action if the script is triggered by it.

ClearTimeout interrupts the count of setTimeout

This method stops the process started with the execution delay and the code associated with this delay.
The process to kill is recognized by the identifier returned by setTimeout.




var x = setTimeout(myfonction, 5000); 

setInterval triggers an operation at regular intervals

Similar to setTimeout, it triggers the same action repeatedly at regular intervals.

setInterval ("instructions", delay)


setInterval ("alert ((beep)", 10000);

Displays a message every ten seconds.
The action will be repeated until you leave the page or clearInterval be executed.

clearInterval stops the action of setInterval

Stops the process triggered by setInterval.


var x = setInterval(myfunction, 10000);

A lambda function may be a parameter

We can define a function inside the setTimeout or setInterval arguments.


var x = setTimeout(function() { alert("bip"); }, 2000);    

The interest here is to use a recursive function, that can be done by referring to the function by the arguments.callee variable.


We will use both functions at once:

The action function after 20 seconds will display the message "THE END" and stop the countdown by calling clearInterval.

Click on the button to begin:

Source code:

<button onclick="start()"> Start the countdown </button>

<div id="bip"></div>

var counter = 10;
var intervalId = null;
function action()
document.getElementById("bip").innerHTML = "THE END!";
function bip()
document.getElementById("bip").innerHTML = counter + " seconds remaining";
function start()
intervalId = setInterval(bip, 1000);
setTimeout(action, counter * 1000);

More demonstrations...

© 2010-2012