1. Tech

Your suggestion is on its way!

An email with a link to:


was emailed to:

Thanks for sharing About.com with others!

Learn Javascript

Times Events

Join the Discussion

Questions? Comments?

Related Terms



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):

continued from previous line +rightBoundary+')',slideDelay);

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.

Past Lessons

  1. Introduction
  2. Decision Making
  3. Functions
  4. Maintain and Test
  5. External Script and Noscript
  6. Object Oriented Javascript
  7. Loops
  8. More Predefined Classes
  9. Document Object Model
  10. Event Handlers

©2016 About.com. All rights reserved.