What is setTimeout, what is it for, and how does it work?

👨‍💻 Frontend Developer 🟡 Often Asked 🎚️ Easy
#JavaScript #Asynchronicity #JS Basics

Quick Answer

setTimeout is a method in JavaScript that allows you to execute a function or code snippet after a specified delay in milliseconds. It does not block the execution of the main code thread; instead, it registers a timer and continues execution. It is a primary tool for creating asynchronous operations, such as delayed notifications, animations, or performing tasks without freezing the user interface. To cancel a timer, clearTimeout is used.


What is setTimeout

setTimeout is a built-in function in browsers and Node.js that allows you to schedule the execution of a function after a certain amount of time. It returns a numeric timer ID that can be used to cancel it.

Syntax

const timerId = setTimeout(callback, delay, ...args);
  • callback: The function to be executed.
  • delay: The delay in milliseconds (1000 ms = 1 second). If not specified, it defaults to 0.
  • ...args: Additional arguments that will be passed to the callback when it is called.

How it works: The Event Loop

setTimeout does not guarantee that the function will execute exactly after the specified time. It guarantees that it will be added to the callback queue no earlier than after the delay.

  1. Calling setTimeout passes the timer to the Web APIs.
  2. The main JavaScript thread continues to execute without blocking.
  3. When the timer expires, the callback is placed in the callback queue.
  4. The Event Loop checks if the call stack is empty.
  5. As soon as the stack becomes empty, the callback from the queue is moved to the stack and executed.

This is why setTimeout(fn, 0) does not execute immediately but is placed at the end of the queue, yielding to the current code.


Usage Examples

1. Simple Delay

console.log("Hello!");
 
setTimeout(() => {
  console.log("This code will run after 2 seconds.");
}, 2000);
 
console.log("This code will not wait.");

Console output:

  1. “Hello!”
  2. “This code will not wait.”
  3. (after 2 seconds) “This code will run after 2 seconds.”

2. Passing Arguments to the Callback

function greet(name, phrase) {
  console.log(`${phrase}, ${name}!`);
}
 
setTimeout(greet, 1500, "Alexander", "Good day");
// Outputs: "Good day, Alexander!" after 1.5 seconds

3. Canceling a Timer with clearTimeout

If you want to cancel a scheduled execution, use clearTimeout, passing it the timerId.

const timerId = setTimeout(() => {
  console.log("This message will never appear.");
}, 5000);
 
console.log(`Timer with ID ${timerId} has started.`);
 
// Cancel the timer after 2 seconds
setTimeout(() => {
  clearTimeout(timerId);
  console.log(`Timer with ID ${timerId} has been canceled.`);
}, 2000);

Practice Problems

Problem 1

// In what order will the numbers appear in the console?
console.log(1);
 
setTimeout(() => console.log(2), 1000);
setTimeout(() => console.log(3), 0);
 
console.log(4);
Answer **Order: `1`, `4`, `3`, `2`**

Explanation:

  1. console.log(1) is executed synchronously.
  2. setTimeout with a 1000 ms delay registers a timer.
  3. setTimeout with a 0 ms delay places console.log(3) in the callback queue.
  4. console.log(4) is executed synchronously.
  5. After the synchronous code finishes, the event loop executes tasks from the queue, starting with console.log(3).
  6. After 1 second, console.log(2) is executed.

Problem 2

// Write a function that logs numbers from 1 to 5
// to the console with a 1-second interval between each number.
 
function printNumbers() {
  // Your code
}
 
printNumbers();
Answer
function printNumbers() {
  for (let i = 1; i <= 5; i++) {
    setTimeout(() => {
      console.log(i);
    }, i * 1000);
  }
}

Explanation: We use let to create a block scope for i. Each loop iteration creates a new i variable, which setTimeout “remembers”. The delay i * 1000 ensures that the numbers are logged sequentially every second.