Working with JavaScript Timeouts and Intervals

By Paul McFedries

JavaScript is an important element in web coding. When you first begin to work with JavaScript, you will likely see the code executed in one of three ways:

  • Automatically when the page loads
  • When your script calls a function
  • In response to some event, such as the user clicking a button

JavaScript also offers a fourth execution method that’s based on time. There are two possibilities:

  • Have some code run once after a specified number of milliseconds. This is called a timeout.
  • Have some code run after a specified number of milliseconds, and then repeat each time that number of milliseconds expires. This is called an interval.

Using a timeout to perform a future action once

To set up a JavaScript timeout, use the window object’s setTimeout() method:

setTimeout(function, delay, arg1, arg2, …)
  • function: The name of a function that you want JavaScript to run when the timeout expires. Instead of a function, you can also use a JavaScript statement, surrounded by quotation marks.
  • delay: The number of milliseconds that JavaScript waits before executing function.
  • arg1, arg2, …: Optional arguments to pass to function.

Note that setTimeout() returns a value that uniquely identifies the timeout. You can store this value just in case you want to cancel the timeout.

Here’s some code that shows how setTimeout() works:

// Create a message
var str = "Hello World!";

// Set the timeout
var timeoutId = setTimeout(logIt, 2000, str);

// Run this function when the timeout occurs
function logIt(msg) {
 
  // Display the message
  console.log(msg);
}

The script begins by creating a message string and storing it in the str variable. Then the setTimeout() method runs:

setTimeout(logIt, 2000, str);

This tells JavaScript to run the function named logIt() after two seconds (2,000 milliseconds) have elapsed, and to pass the str variable to that function. The logIt() function takes the msg argument and displays it in the console.

If you’ve set up a timeout and then decide that you don’t want the code to execute after all for some reason, you can cancel the timeout by running the clearTimeout() method:

clearTimeout(id);
  • id: The name of the variable that was used to store the setTimeout() method’s return value

For example, suppose you set a timeout with the following statement:

var timeoutId = setTimeout(logIt, 2000, str);

Then you’d cancel the timeout using the following statement:

clearTimeout(timeoutId);

Using an interval to perform a future action repeatedly

Running code once after a specified number of seconds is only an occasionally useful procedure. A much more practical skill is being able to repeat code at a specified interval. This enables you to set up countdowns, timers, animations, image slide shows, and more. To set up an interval, use the window object’s setInterval() method:

setInterval(function, delay, arg1, arg2, …)
  • function: The name of a function that you want JavaScript to run at the end of each interval. Instead of a function, you can also use a JavaScript statement, surrounded by quotation marks.
  • delay: The number of milliseconds in each interval, after which JavaScript executes function
  • arg1, arg2, …: Optional arguments to pass to function

As with setTimeout(), the setInterval() method returns a value that uniquely identifies the interval. You use that value to cancel the interval with the clearInterval() method:

clearInterval(id);
  • id: The name of the variable that was used to store the setInterval() method’s return value

For example, suppose you set an interval with the following statement:

var intervalId = setInterval(countdown, 5000);

Then you’d cancel the interval using the following statement:

clearInterval(intervalId);

Note that although the clearTimeout() method is optional with setTimeout(), you should always use clearInterval() with setInterval(). Otherwise, the interval will just keep executing.

The following code demonstrates both setInterval() and clearInterval().

var counter = 10;

// Set the interval
var intervalId = setInterval(countdown, 1000);

// Run this function at the end of each interval
function countdown() {

  // Display the countdown and then decrement the counter
  console.log(counter--);
 
  // Cancel the interval when we hit 0
  if (counter < 0) {
    clearInterval(intervalId);
    console.log("All done!");
  }
}

The purpose of this script is to display a countdown from 10 to 0 in the console. The script begins by declaring a variable named counter and initializing it to 10. Then the setInterval() method sets up a function named countdown() to run at intervals of one second (1,000 milliseconds). The countdown() function displays the current value of counter in the console and then decrements counter. Then an if() test checks the value of counter. If it’s negative, it means that counter was just 0, so it’s done. The clearInterval() method cancels the interval, and then a final console message is logged.