Node.js Timers Module

⏱️ Node.js – Timers Module

The Timers module allows you to schedule functions to run after a delay or periodically, similar to JavaScript in the browser.

Timers are global functions in Node.js, so you do not need to import any module.


1. setTimeout()

Runs a function once after a specified delay.

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

2. setInterval()

Runs a function repeatedly at a given interval.

setInterval(() => {
console.log("Repeating every 1 second");
}, 1000);

3. setImmediate()

Runs a function immediately after the current event loop cycle.

setImmediate(() => {
console.log("Runs immediately after current execution");
});

4. clearTimeout()

Cancels a setTimeout() timer.

const timer = setTimeout(() => {
console.log("I will not run");
}, 3000);

clearTimeout(timer); // canceled


5. clearInterval()

Stops a running interval.

const interval = setInterval(() => {
console.log("This will stop soon");
}, 1000);

setTimeout(() => {
clearInterval(interval);
console.log("Interval stopped!");
}, 5000);


6. clearImmediate()

Cancels a setImmediate().

const immediate = setImmediate(() => {
console.log("Canceled immediate");
});

clearImmediate(immediate);


7. Timers with Arguments

You can pass arguments to your timer function.

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

setTimeout(greet, 2000, "Vipul");


8. Nested Timers (Example)

setTimeout(() => {
console.log("Step 1");

setImmediate(() => {
console.log("Step 2");
});

}, 1000);


9. Using Timers with Event Loop

Timers run asynchronously, and their execution depends on:

  • Event loop phase

  • System delays

  • Timer queue state

Example:

console.log("Start");

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

console.log("End");

Output:

Start
End
Timeout

Because even 0ms timeout waits for the event loop.


⭐ Complete Example (All Timers)

console.log("Start");

setTimeout(() => {
console.log("After 1 sec");
}, 1000);

const interval = setInterval(() => {
console.log("Every 2 sec");
}, 2000);

setTimeout(() => {
clearInterval(interval);
console.log("Interval cleared");
}, 7000);

setImmediate(() => {
console.log("Immediate call");
});

console.log("End");


🎯 Where Timers Are Used in Node.js

✔ Cron jobs
✔ Scheduling tasks
✔ Retry operations
✔ Delayed API calls
✔ Polling servers
✔ Animation counters
✔ Queue processing

You may also like...