Home > Articles > Open Source > Ajax & JavaScript

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Adding Timers

Another useful feature of JavaScript is the ability to set timers that execute a function or evaluate an expression after a certain amount of time or on a specific interval.

Using timers allows you to delay the execution of code so that it does not need to happen at the exact moment an event is triggered or the page is loaded. The following phrases show you how to create timers to delay code execution and to apply recurring actions.

Adding a Delay Timer

To simply delay the execution of code for a certain amount of time, use the setTimeout(code, ms) method, where code is either a statement or a function that executes when the time expires. ms is the number of milliseconds. For example, to execute a function named myTimer() in 10 seconds, you would use the following:

setTimeout(myTimer, 10000);

Cancel a Timer

At any point before the time runs out and the code is executed, you can clear the timer by calling the clearTimeout(id) method using the ID returned from setTimeout(). Once the timer has been cleared, it does not execute. You need to keep track of the ID returned from setTimeout() using a variable.

Adding a Recurring Timer

You can also start a timer that triggers on a regular interval using the setInterval(function, ms) method. This method also accepts a function name and milliseconds as arguments. Inside the function, you need to call set interval again on the same function so that the code will be called again.

To turn off the recurring timer, simply do not call setInterval() again inside the timer function, or use clearInterval() outside the function.

  • + Share This
  • 🔖 Save To Your Account