Understanding setTimeout and setInterval in JavaScript

What are setTimeout and setInterval?

setTimeout and setInterval are built-in Web API methods provided by browsers to schedule tasks:

⚠️ Important Notes

How JavaScript Executes Timers – The Event Loop

JavaScript is single-threaded and uses an Event Loop to handle asynchronous tasks like timers.

The 3 Phases of Execution

  1. Call Stack: JavaScript runs code line-by-line. When it finds a timer like setTimeout, it sends it to...
  2. Web APIs: Browser timers handle the countdown in the background.
  3. Callback Queue: Once the timer finishes, the callback is moved here and waits until the call stack is empty.

The Event Loop constantly checks the stack. When it's empty, it pushes the next callback from the queue to the stack for execution.

Visual Demo

The GIF below shows how Call Stack → Web APIs → Callback Queue work together.

Event Loop Demo with Timers

Examples

1. setTimeout with Function


function greet() {
  console.log("Hello from setTimeout!");
}
setTimeout(greet, 2000);
    

2. setTimeout with Arrow Function


setTimeout(() => {
  console.log("Executed after 3 seconds.");
}, 3000);
    

3. setInterval Example


const intervalId = setInterval(() => {
  console.log("Repeating every 5 seconds.");
}, 5000);
    

4. Clearing Timeout and Interval


clearTimeout(timerId);     // Cancels a timeout
clearInterval(intervalId); // Cancels a repeating interval
    

5. Event Loop Execution Example


console.log("Start");

setTimeout(() => {
  console.log("Inside setTimeout");
}, 0);

console.log("End");

// Output:
// Start
// End
// Inside setTimeout