Creating a timer in JavaScript using setInterval

Written by
Published on
Modified on
Category

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 Guevara is a software engineer, startup founder and currently teaches programming for a coding bootcamp. He is currently building things that don't yet exist.

Comments

No messages posted yet

Developer Poll 🐱‍💻

Q:

Add a comment

Send me your weekly newsletter filled with awesome ideas
Post