JavaScript setTimeout()

Introduction

JavaScript is a single-threaded language, which means it can execute one task at a time. However, it can still handle asynchronous operations efficiently using features like callbacks, event loop, and Web APIs. One of the most commonly used asynchronous functions in JavaScript is setTimeout().

The setTimeout() function allows you to execute a piece of code after a specified delay. It is widely used for tasks like delaying execution, scheduling actions, creating animations, and handling asynchronous workflows.

In this article, we will explore everything about setTimeout(), including its syntax, working mechanism, real-life use cases, and common mistakes.

What is JavaScript setTimeout()?

setTimeout() is a built-in JavaScript function that executes a function or code block after a specified delay (in milliseconds).

In simple terms:

setTimeout() = Run code after a delay

πŸ“–
Important:
  • Executes code after a delay.
  • Works with the event loop.
  • Does not guarantee exact timing.
  • Can be cancelled using clearTimeout.

Basic Example


setTimeout(function () {
 console.log("Hello after 2 seconds");
}, 2000);

Output appears after 2 seconds.

Why setTimeout() is Used

setTimeout() is widely used in real-world applications for:

1. Delayed Execution

Run code after a certain time.

2. User Experience Enhancements

Show notifications, loaders, or animations.

3. API Handling

Simulate or delay API calls.

4. Scheduling Tasks

Execute functions at a later time.

5. Event Handling

Control timing of events.

Syntax


setTimeout(function, delay, param1, param2, ...);

Parameters:

  1. function β†’ Function to execute
  2. delay β†’ Time in milliseconds (1000 ms = 1 second)
  3. parameters (optional) β†’ Values passed to the function

Example with Parameters


function greet(name) {
 console.log("Hello " + name);
}

setTimeout(greet, 2000, "John");

How setTimeout() Works (Event Loop Concept)

setTimeout() looks simple, it works with the JavaScript event loop.

Step-by-step Process:

  1. Code runs in the Call Stack.
  2. setTimeout() is sent to Web APIs.
  3. Timer starts in the background.
  4. After delay, callback goes to Callback Queue.
  5. The Event Loop pushes it back onto the Call Stack when it’s empty.

Note: setTimeout() does not guarantee exact timing, only minimum delay.

Example:


console.log("Start");

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

console.log("End");

Output:

Start
End
Middle

Example of different use cases

Example 1: Basic Delay


setTimeout(() => {
 console.log("Executed after 1 second");
}, 1000);

Example 2: Cancel setTimeout


let timer = setTimeout(() => {
 console.log("Will not run");
}, 2000);

clearTimeout(timer);  // Cancel setTimout

Example 3: Repeating Task Using setTimeout


function repeat() {
 console.log("Running...");
 setTimeout(repeat, 1000);
}

repeat();

Example 4: Dynamic Delay


for (let i = 1; i <= 3; i++) {
 setTimeout(() => {
   console.log(i);
 }, i * 1000);
}

Real-Life Example:

1. Showing Notification After Delay

You can use the example below in chatApps, Reminders, and Alerts.


function showNotification() {
 console.log("New Message Received!");
}

setTimeout(showNotification, 3000);

2. Loading Spinner

This is mostly used when you get the API response.


console.log("Loading...");

setTimeout(() => {
 console.log("Data Loaded");
}, 2000);

Common Mistakes of setTimeout()

1. Using String Instead of Function

When Beginners use a string instead of a function, this is a Bad practice.


setTimeout("console.log('Hello')", 1000); // Bad practice

2. Forgetting clearTimeout


let timer = setTimeout(() => {}, 5000);
// Not cleared β†’ unnecessary execution

3. setTimeout Inside Loop Issue


for (var i = 1; i <= 3; i++) {
 setTimeout(() => console.log(i), 1000);
}

Output:

4, 4, 4

Interview Questions

Q 1: What is setTimeout()?
Ans: A function that executes code after a specified delay.
Q 2: Does setTimeout guarantee exact timing?
Ans: No, it guarantees minimum delay.
Q 3: What is the difference between setTimeout and setInterval?
Ans: setTimeout β†’ runs once
setInterval β†’ runs repeatedly
Q 4: How to cancel setTimeout?
Ans: clearTimeout(timerId);
Q 5: Why does setTimeout with 0 delay still wait?
Ans: Because it goes through the event loop and callback queue.

Conclusion

JavaScript setTimeout() is a powerful and essential function for handling delayed and asynchronous operations. Whether you’re building animations, handling API calls, or improving user experience, setTimeout() plays a crucial role.