Javascript Timers

Posted on March 6th, 2010 by Eric Rowell

Javascript timers can be very handy when developing advanced scripts.  I’ve found that timers are most useful when creating RIA (rich internet application) elements, like making a div fade out over a period of a few seconds, waiting a small period of time to show a div, or waiting a short period of time to initialize a specific Javascript function.  The key to creating a Javascript timer is the setTimeout() function.  It takes two parameters.  The first parameter is the function that the timer will call, and the second parameter is the number of milliseconds to wait before calling.  In the example below, when startTimer() is called, an alert will pop up after five seconds.

1
2
3
4
5
var t;
 
function startTimer() {
   t=setTimeout("alert('5 seconds!')",5000);
}

It can also be very useful to cancel the timer event.  in the code above, we set the time to a variable t, so that it can be referenced in case we would like to stop the timer.  To do this, we will need to use the clearTimeout() function which only takes one parameter, the setTimeout() event, t.

1
2
3
function cancelTimer() {
   clearTimeout(t);
}

Tags: , , ,

One Response to “Javascript Timers”

  1. very cool & good js timer, thank you very much for sharing.

Leave a Reply