Course contentsShow
← JavaScript
Lesson 1471 of 2,72332. JavaScript in the BrowserFree lesson

Timers: setTimeout and setInterval

Scheduling code execution with setTimeout for delays and setInterval for repeated execution.

Timers: setTimeout and setInterval

You'll learn how to schedule code to run after a delay or on a repeating schedule using JavaScript's built-in timer functions.

The Core Idea

JavaScript provides two essential timer functions: setTimeout and setInterval. Think of setTimeout as setting an alarm clock—it runs your code once after a specified delay. setInterval is like a recurring alarm that keeps going off at regular intervals until you turn it off.

Both functions are part of the browser's window object (and available in Node.js too) and allow you to control when your code executes, rather than running everything immediately.

setTimeout: Delayed Execution

setTimeout schedules a function to run once after a specified number of milliseconds:

setTimeout(() => {
  console.log('This runs after 2 seconds');
}, 2000);

The first argument is the function to execute, and the second is the delay in milliseconds (1000ms = 1 second).

setInterval: Repeated Execution

setInterval runs a function repeatedly at a fixed time interval:

setInterval(() => {
  console.log('This repeats every 3 seconds');
}, 3000);

This continues indefinitely until you stop it manually.

Canceling Timers

Both functions return an ID that you can use to cancel them:

const timerId = setTimeout(() => console.log('Hello'), 5000);
clearTimeout(timerId); // Cancels before it runs

const intervalId = setInterval(() => console.log('Tick'), 1000);
clearInterval(intervalId); // Stops the repeating timer

Key Takeaway: Use setTimeout to delay code execution once and setInterval for repeated execution at regular intervals; both return IDs that let you cancel them with clearTimeout or clearInterval.