Home > Articles

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

How to Set and Use Timers

In some situations you’ll want to program a specific delay into the execution of your JavaScript code. This type of delay is especially common when writing user interface routines; for instance, you may want to display a message for a short period before removing it.

To help you, JavaScript provides two useful methods: setTimeout() and setInterval().


The setTimeout(action, delay) method calls the function (or evaluates the expression) passed in its first argument after the number of milliseconds specified in its second argument. You can use it, for example, to display an element in a given configuration for a fixed period of time:

<div id="id1">I'm about to disappear!</div>

Let’s suppose your page contains the preceding <div> element. If you put the following code into a <script> element in the page <head> section, the function hide() will be executed 3 seconds after the page finishes loading, making the <div> element invisible:

function hide(elementId) {
    document.getElementById(elementId).style.display = 'none';
window.onload = function() {
    setTimeout("hide('id1')", 3000);

The setTimeout() method returns a value. If later you want to cancel the timer function, you can refer to it by passing that returned value to the clearTimeout() method:

var timer1 = setTimeout("hide('id1')", 3000);


The setInterval(action, delay) method works similarly to setTimeout(), but instead of imposing a single delay before executing the statement passed to it as its first argument, it executes it repeatedly, with a delay between executions corresponding to the number of milliseconds specified in the second argument.

Like setTimeout(), setInterval() returns a value that you can later pass to the clearInterval() method to stop the timer:

var timer1 = setInterval("updateClock()", 1000);
  • + Share This
  • 🔖 Save To Your Account