ProgrammingJavascriptCareerProductivityGadgetsASP.NETWeb Design

Creating a timer in JavaScript using setInterval

Written by
Published on
Modified on
Filed under
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 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:

Stay up to date

Sign up for my FREE newsletter. Get informed of the latest happenings in the programming world.

Add a comment

Keep me up to date on the latest programming news
Add Comment

Stay up to date

Get informed of the latest happenings in the programming world.

No thanks