JavaScript setTimeout and setInterval

Posted under JavaScript on December 22, 2009.

JavaScript has two functions that allow you to implement a delay before activating another function. In this article I will show you the difference between the setTimout and setInterval functions and how to use them.

setTimout

The setTimeout function is used to delay the activation of a function once. The following example delays for two seconds before alerting "Hello, World!":

var timer = setTimeout(function(){

	alert('Hello, World!');

},2000);

You can stop a delayed function from running at any time by using the clearTimeout function:

clearTimeout(timer);

setInterval

The setInterval function works exactly like the setTimeout function, but after activating the delayed function it starts another delay to run the function again. You can think of it as an infinite loop with a delay. Here is an example of using setInterval to create a second counter that stops at ten seconds:

var x = 0;
var timer = setInterval(function(){

	x = x + 1;
	
	if(x == 10)
	{
		alert('Done!');
		clearInterval(timer);
	}

},1000);

As you can see from the above example, you can use clearInterval to stop the loop. Possible uses for the setInterval function include scripts that have to query the server every so often (chatrooms, feed readers) or counters and timers.

Comment

See what others have to say on this topic, or add your own two cents.