Learn Javascript
Times Events
Join the Discussion
More of this Tutorial
Related Terms
Introduction
There will often be times (particularly if you are creating animated effects) where you want a piece of Javascript code to run after a set amount of time has passed. You may even want the code to run over and over at set intervals. To do this we need to use time event handlers.
SetTimeout and SetInterval
The setTimeout() event handler will run Javascript code that you want to run after a specified amount of time has passed. Unlike the event handlers we have looked at so far this event handler is coded within your Javascript instead of being added to an HTML tag. You call the setTimeout() event handler as a function passing it two parameters. The first parameter is a text string containing the code to be run (usually you would call a function) and the second parameter is the time to wait before running that code (specified in milliseconds). Here is an example (from the scrolling Ads script):
In this example the function waits for the amount of time specified in the slideDelay field and then calls the slideAd function passing three parameters.
The setInterval() function works similarly to setTimeout except that while the setTimeout will run the specified function once after the specified delay the setInterval will run the function again and again after waiting the required time.
ClearTimeout and ClearInterval
Another event might occur during the time delay period between the running of the setTimeout or setInterval function and its running the specified code that means that you no longer want that code to run. By assigning the value returned from the setTimeout or setInterval function to a variable we can pass that variable to the clearTimeout or clearInterval function to cancel the timer.
Using What You Know
By combining the timed event handlers with any of the other event handlers that you already know you will be able to delay the running of the code triggered by that event by a set amount of time.

