Node.js provides a built-in timer module, which is part of the events module. It includes functions for scheduling tasks, executing cron jobs, recurring tasks, and cancelling timer-based events.
The primary function for creating timers is setTimeout, and there's also setInterval for recurring events.
Here's a basic overview of the timer-related functions:
Executes a callback function after a specified delay (in milliseconds). Optionally, we can pass additional arguments to the callback.
setTimeout(() => { console.log('Delayed function executed.'); }, 2000); // Execute after 2000 milliseconds (2 second)
Output:-> `Delayed function executed` will get print after 2 seconds delay.
Similar to `setTimeout`, but the callback function of `setInterval` is executed repeatedly at the specified interval. similarly, we have created a `setTimeout` function against `intervalId` to `clearInterval` after a specified period.
// stop interval after 5.1 second. let countSecond = 0; const intervalId = setInterval(() => { countSecond++; console.log(`Executed ${countSecond} times.`); }, 1000); // Execute every 1000 milliseconds (1 second) // To stop the interval after a certain time (e.g., after 5.1 seconds) setTimeout(() => { clearInterval(intervalId); console.log('Stop Interval.'); }, 5100);
Executed 1 times. Executed 2 times. Executed 3 times. Executed 4 times. Executed 5 times. Stop Interval.
Used to cancel a scheduled `timeout` or `interval`. Pass the timer ID returned by `setTimeout` or `setInterval` to clear it.
const timeoutId = setTimeout(() => { console.log('This will never be executed.'); }, 3000); clearTimeout(timeoutId); // The timeout will be canceled, and the callback won't be executed. const intervalId = setInterval(() => { console.log('This will never be executed.'); }, 1000); clearInterval(intervalId);
Schedules a callback function to be invoked in the next iteration of the event loop. It is not technically a timer, but it is often discussed in the context of timers.
process.nextTick(() => { console.log('it will get executed in next tick of the event loop.'); });