![]() |
VOOZH | about |
The Timers module in Node.js allows execution of code after a specified delay or at repeated intervals. It is a global module, so it can be used without importing it.
In Node.js, timers can be categorized into two types based on their purpose.
Scheduling timers allow functions to execute after a delay or at repeated intervals. They help manage timed and asynchronous execution of code.
1. setImmediate() method: schedules a callback to execute immediately after I/O events in the event loop. Callbacks run in the order they are created after each event loop iteration.
Started... 1 3 2 4
2. setInterval() method: repeatedly executes a callback function after every specified time interval (in milliseconds) until it is stopped using clearInterval().
Output
Executed before A...
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
...
3. setTimeout() method: schedules the execution of a callback function once after a specified delay (in milliseconds).
Output
Executed before A...
Hello World!
Canceling timers is used to stop or prevent the execution of previously scheduled timer functions. It helps control timer-based operations in Node.js applications.
1. clearImmediate() method: cancels an Immediate object created by setImmediate(), preventing the scheduled callback from executing.
2
2. clearInterval() method: cancels the timer created by setInterval(), stopping the repeated execution of the callback function.
Output
Hello World!
Hello World!
Hello World!
Hello World!
3. clearTimeout() method: cancels the timer created by setTimeout(), preventing the scheduled callback from executing.
Output
Hello Geeks!