Timing events in Javascript with setTimeout and setInterval

Posted on 15-03-2013 16:35 by graham
In Javascript, you can schedule a function to be called at some later point in time.

Scheduling events using the setTimeout method


To schedule an event, use the setTimeout (code, timeoutInMilliseconds) method. The first parameter passed to this method is the Javascript code to be executed, the second parameter is a time interval in milliseconds after which the event will be executed.
function sayHello()
{
alert("Hi there!");
}

// call method sayHello after 3000ms
setTimeout (sayHello(), 3000);

You can also try this out and play with the code using our sandbox.

Clearing the scheduled event


Of course it may happen that you will want to unschedule the event. To do this, we have to assign the timer to some variable and then call function clearTimeout function:
var timer = setTimeout (sayHello(), 3000);
clearTimeout(timer);


The setInterval function


Function setTimeout scheduled an event to be executed once. If, however, you want the piece of code to be executed over and over again at certain intervals of time, you should use setInterval (code, intervalMilliseconds).

Similarly as with setTimeout, you can unscheduled the execution by calling clearInterval.
var num = 0;
var timer = setInterval (function() { countToFive(); }, 1000);
function countToFive()
{
if (num <= 5)
{
alert(num++);
}
else
{
clearInterval(timer);
}
}

Try it out in our demo.
Comments

 

Add comment

Has this tutorial been helpful to you? Or do you see anything wrong? We appreciate your opinion!
Your comment:
Show formatting hints
HTML is disallowed, but in your text you can use the following markup
  • [code][/code] for a block of code
  • [tt][/tt] for inline code
  • [link]link href|link anchor[/link] for links
  • [b][/b] for bold text
Email:
+ Ask a question
If you have a technical question related to programming and computers, ask it here. Other users will help you solve it!
Unanswered questions
Share your knowledge by helping others solve their problems