Menu

Creating a timer in JavaScript using setInterval

Creating a timer in JavaScript using setInterval

Performing certain tasks on a website every 'n' number of seconds can be very useful when trying to achieve certain effects, such as creating on-screen visible timers, polling for data or even counting down towards some event.

The setInterval() method of the window interface help us do just that.

Note that setInterval() does not have to be prefixed by its interface when calling it. The function returns back to the caller an ID, generated automatically, that will be used to uniquely identify the timer. This will be useful in case you are working with multiple timers and need to clear them individually.

var timer;

function start(){
    timer = setInterval(function(){
    }, 1000);
}

The setInterval() method has 2 required parameters. Those being the function (named or anonymous) that is to be called on each interval, and an 32-bit integer representing the number of milliseconds between each interval call.

You can also include optional arguments after the 2nd. Those will be passed to the named function that is the 1st argument.

var timer;

function start(){
	timer = setInterval(callthis, 1000, "arg1", "arg2");
}

function callthis(arg1, arg2){
	console.log(arg1 + ' ' + arg2);
	// "arg1 arg2"
}

Optional arguments will not work in IE9 and below.

Clearing the timer

Once you are done with the timer, the built-in clearInterval(id) method can be used. This function takes in 1 argument, the ID of the timer that we wish to clear.

var timer;

function start(){
	timer = setInterval(function(){

	}, 1000);
}


function stop(){
	clearInterval(timer); // timer holds the ID of this particular timer
}

If your aim is to call a function one time only after a set interval of time, then the setTimeout() function might be more appropriate.

Walter G. author of blog post
Walter Guevara is a Computer Scientist, software engineer, startup founder and previous mentor for a coding bootcamp. He has been creating software for the past 20 years.

Get the latest programming news directly in your inbox!

Have a question on this article?

You can leave me a question on this particular article (or any other really).

Ask a question

Community Comments

No comments posted yet
Ad Unit

Current Poll

Total Votes:
Q:
Submit

Add a comment