Introduction
setImmediate() is primarily used in server-side JavaScript environments like Node.js to schedule a callback to run after the current event loop phase completes.
Where is setImmediate used?
When working with asynchronous operations—especially in server-side environments—you may need to execute a function immediately after the current operation completes, but without blocking the execution flow.
In this article, we will explore what setImmediate() is, how it works, its syntax, examples, real-world usage, and how it differs from other timing functions.
What is JavaScript setImmediate()?
setImmediate() is a function that schedules a callback to be executed immediately after the current code execution completes, in the next iteration of the event loop.
In simple terms:
setImmediate() = Execute code right after the current task finishes
- Executes code after current operation.
- Mainly used in Node.js.
- Works in event loop check phase.
- Useful for non-blocking operations.
- Alternative to setTimeout(0).
Syntax
setImmediate(callback, arg1, arg2, ...);
Parameters:
- callback → Function to execute
- arguments (optional) → Values passed to the function
Basic Example
setImmediate(() => {
console.log("Executed immediately after current code");
});
console.log("Hello");
Output:
Executed immediately after current code
Example with Parameters
function greet(name) {
console.log("Hello " + name);
}
setImmediate(greet, "John");
Why setImmediate() is Used
setImmediate() is useful in specific scenarios:
1. Non-Blocking Execution
Allows heavy operations to be deferred.
2. Better Performance
Prevents blocking the event loop.
3. Task Scheduling
Executes tasks after current operations.
4. Server-Side Development
Commonly used in Node.js applications.
How setImmediate() Works
To understand setImmediate(), you need to know about the event loop phases in Node.js.
Execution Flow:
- Code runs in Call Stack
- setImmediate() callback is placed in Check Phase Queue
- After I/O events and timers
- Event loop executes setImmediate() callbacks
Note: It runs after I/O events but before closing callbacks.
Example
Let’s explore different use cases.
Example 1: Basic Usage
setImmediate(() => {
console.log("Immediate execution");
});
Example 2: Comparing with setTimeout
setTimeout(() => {
console.log("Timeout");
}, 0);
setImmediate(() => {
console.log("Immediate");
});
Output order may vary depending on the environment.
Example 3: Non-Blocking Loop
function processItems() {
for (let i = 0; i < 5; i++) {
console.log("Processing " + i);
}
setImmediate(() => {
console.log("Finished processing");
});
}
processItems();
Example 4: With I/O Operations
const fs = require("fs");
fs.readFile("file.txt", () => {
setImmediate(() => {
console.log("After file read");
});
});
Real-Life Example
I will show you two Real Life Example.
1. Server Handling Requests
function handleRequest() {
console.log("Request received");
setImmediate(() => {
console.log("Processing request...");
});
}
handleRequest();
2. Breaking Heavy Tasks
Prevents blocking event loop.
function heavyTask() {
let i = 0;
function chunk() {
for (let j = 0; j < 1000; j++) {
i++;
}
if (i < 10000) {
setImmediate(chunk);
}
}
chunk();
}
heavyTask();
Common Mistakes
You will see some common mistakes.
1. Using in Browser
setImmediate(() => {}); // ❌ not supported in browsers
2. Confusing with setTimeout(0)
setTimeout(fn, 0);
setImmediate(fn);
They behave differently in event loop phases.
3. Infinite Loops
function loop() {
setImmediate(loop);
}
Can cause performance issues.
JavaScript setImmediate() method – Interview Questions
Q 1: What is setImmediate()?
Q 2: Is setImmediate available in browsers?
Q 3: Difference between setTimeout and setImmediate?
Q 4: Is setImmediate asynchronous?
Q 5: Use case of setImmediate()?
Conclusion
JavaScript setImmediate() is a powerful tool for scheduling tasks efficiently in Node.js. It helps prevent blocking, improves performance, and provides better control over asynchronous execution.
setImmediate() is used to build high-performance, non-blocking applications, especially on the server side.
JavaScript setImmediate() method – Objective Questions (MCQs)
Q1. setImmediate() executes code ______.
Q2. setImmediate() is mainly used in ______.
Q3. Which method cancels setImmediate()?
Q4. setImmediate() returns a ______.
Q5. setImmediate() belongs to which phase of the event loop?