JavaScript: difference between setTimeout and setInterval

In JavaScript, timers are created through the setTimeout() and setInterval() global functions. There's an important difference between the two: setTimeout() delays the execution of a routine for a certain amount of time and then stops, whereas setInterval() repeats such routine over and over again. Both functions are vital for creating repeated JavaScript animations or just for monitoring the execution of your code over a specific time span.

The syntax of both functions is the same:

setTimeout(callback, time);
setInterval(callback, time);

where callback is a function or routine to be executed, and time is a number that specifies the delay in milliseconds (so 1 second is 1000).

For example:

function say()

setTimeout(say, 3000);

After three seconds, you will simply see an alert with the 'Hi!' string inside and then the routine finishes its cycle and nothing else happens. Instead, with setInterval() you will see the same alert every three seconds, over and over again.

However, many JavaScript developers prefer to avoid setInterval() and use setTimeout() in this way for creating repeated routines:

setTimeout(function() {

  setTimeout(arguments.callee, 3000);

}, 3000);

In this case, the perceived final effect is the same as using setInterval() but the time queue is better controlled in this example.

One word about scope and visibility: if you're using these functions within your objects or framework calls, the best way to make sure that both functions will work is to use the extended reference window.setTimeout() and window.setInterval().

Leave a Reply

Note: Only a member of this blog may post a comment.