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.
⭐ 2. setInterval()
Runs a function repeatedly at a given interval.
⭐ 3. setImmediate()
Runs a function immediately after the current event loop cycle.
⭐ 4. clearTimeout()
Cancels a setTimeout() timer.
⭐ 5. clearInterval()
Stops a running interval.
⭐ 6. clearImmediate()
Cancels a setImmediate().
⭐ 7. Timers with Arguments
You can pass arguments to your timer function.
⭐ 8. Nested Timers (Example)
⭐ 9. Using Timers with Event Loop
Timers run asynchronously, and their execution depends on:
-
Event loop phase
-
System delays
-
Timer queue state
Example:
Output:
Because even 0ms timeout waits for the event loop.
⭐ Complete Example (All Timers)
🎯 Where Timers Are Used in Node.js
✔ Cron jobs
✔ Scheduling tasks
✔ Retry operations
✔ Delayed API calls
✔ Polling servers
✔ Animation counters
✔ Queue processing
