Timer in JavaScript


In this post we will talk about timers and their usage in JavaScript

Timers are available in the Window object. It takes two parameters the time in milliseconds and expression or the function. We have 2 types of timers:

setInterval (func, milliseconds) – this timer is recursive and will evaluate the expression each time when the timespan that we have specified occurs.

setTimeout (func, milliseconds) – this timer is executes the expression once when the timespan we specified is passed.

We also have clear method available on both types of timers.

clearInterval (id) – takes the id of the timer to clear so that the specified code is not executed at specified intervals.

clearTimeout (id) – takes the id of the timer to clear so that the specified code is not executed at specified timeout time.

Another thing to keep in mind about the timers is that the timers run on the same thread as the UI events. All JavaScript in the browser executes in the single thread asynchronous events and this forces JavaScript asynchronous events to queue waiting for execution. So whenever we specify time for a timer we can be sure that it will not fire before the specified time. Generally the delays are unnoticeable by the end users.


This type of timers are useful at places where we want to execute a block of code after a specified amount of time or at some timeout.

function setTimeoutSample() {

setTimeout(onTimeout, 2000);


function onTimeout() {

console.log("Timeout has occurred!!");



Recurring function call

This timer is useful when we want to call a function for multiple times at some specified interval. May be useful when we are performing some time based actions or animations.

var countInterval = 0;

function onTimeout() {


console.log(countInterval + ". Interval has occurred!!");


function setIntervalSample() {

setInterval(onTimeout, 2000);


Clear Interval

This function clears the Interval timer and it will not execute any further.

var countIntervalClearable = 0;

function onTimeoutClearable() {


console.log(countIntervalClearable + ". Interval has occurred!!");

if (countIntervalClearable >= 5) {




var intervalId = setInterval(onTimeoutClearable, 2000);


Instead of passing a global function we can also pass an anonymous function in the setInterval timer.

The code for this post can be found here.

Any questions, comments or feedback is most welcome.

Leave a Reply

Your email address will not be published. Required fields are marked *