Node.js – Timer Module
Subject: nodejs
Node.js – Timer Module
The Timer module in Node.js provides functions to execute code after a specific delay or at regular intervals. These functions are similar to JavaScript timers used in browsers, but they are part of the Node.js runtime and operate at the event loop level.
These timer functions are globally available in Node.js, meaning you don’t need to import any module to use them.
Why Use Node.js Timer Functions?
- To schedule one-time or repeating tasks (like logs, backups).
- To delay the execution of a function.
- To simulate polling or heartbeat functions.
- To control asynchronous behavior.
Timer Functions in Node.js
1. setTimeout() – Delayed Execution
Explanation: Executes the callback once after 2000ms. Commonly used for simulating delay or waiting before retries.
2. setInterval() – Repeated Execution
Explanation: Executes the callback every 1000ms until cleared. Useful for polling, repeated logs, or status checks.
3. clearTimeout() and clearInterval()
4. setImmediate() – Run After Current Event Loop Phase
Output:
Explanation: Executes the callback after I/O events, not after a set time. Faster than setTimeout(..., 0)
in some cases.
Real-World Use Cases
- Retry logic for failed HTTP requests using
setTimeout
- Monitoring system status with
setInterval
- Deferring CPU-heavy operations with
setImmediate
- Canceling scheduled operations gracefully using
clear*
functions
Key Takeaways
- Timer functions in Node.js help manage delayed and repeated execution of code.
setTimeout
,setInterval
, andsetImmediate
are globally available.- You can cancel any timer with their corresponding
clear*
functions. - These timers integrate tightly with Node's event loop, ensuring efficient scheduling.