tutorialstonight logo


Timers in javascript provide a functionality to delay the function call for a certain time or to call a function continuously after a regular interval of time.

There are 2 different types of timer function in javascript:

  • setInterval(function, milliseconds) - This executes a function at a regular interval of time (in milliseconds)
  • setTimeout(function, milliseconds) - This executes a function after the given amount of time (in milliseconds)

Let's look at some scenarios and see what javascript functionality to use to invoke functions in the given scenarios.

Scenario What to use
To invoke function for 'n' number of times Use javascript loop, loop for 'n' number of times and invoke function in each iteration
To invoke a function on some event Use 'addEventListener' method and bind the function with desired event
Invoke a function after some time Use setTimeout() method
Invoke a function regularly at a certain interval of time Use setInterval() method

The setInterval Method

The setInterval() method executes a function repeatedly after a fixed interval of time.

The setInterval() method is a method of window interface, hence it is a global method.

setInterval(function, milliseconds);

The setInterval() method contains 2 parameters:

  • function - It is a function that user you want to invoke
  • Time - It is given time (in milliseconds) after which function repeats its execution

In the following example the setInterval function repeatedly prints counting after 1 second.

How To Stop setInterval() From Calling A Function?

If you don't stop the setInterval method from calling the function then it will keep execution the function till infinity. So we need to stop the interval.

To stop the setInterval() method use clearInterval() method and pass the instance of setInterval() function (When called setInterval() method it returns an instance which can be stored in a variable).

var intervalInstance = setInterval();

The following example contains a button which onclick clears interval of counter function.

The setTimeout Method

The setTimeout() method executes a function after a specified time interval.

The setTimeout() method receives two parameter :

  • function - It is a function that user you want to invoke
  • Time - It is given time (in milliseconds) after which function is executed

The following example shows the current time after 3 seconds.

How To Stop setTimeout() From Calling A Function?

The clearTimeout() method stops the function execution in setTimeout().

The clearTimeout() method is a window method, so can be used with or without referring to the window

var timeoutReference = setTimeout();

The setTimeout() method returns a reference which is passed in the clearTimeout() as an argument to clear timeout.

The following method prints time after three second, stopping it from printing by clearing setTimeout().

Javascript Timers