Using Timers to Schedule Tasks

Explore how to use setTimeout and setImmediate to schedule tasks asynchronously.
// Schedule a function to run after a specified delay using setTimeout
setTimeout(() => {
  console.log('This message is logged after a 2 second delay');
}, 2000);
This code schedules a one-time task to be executed after a 2-second delay. The setTimeout function takes a callback function and a time in milliseconds.
// Use clearTimeout to cancel a setTimeout call
const timeoutId = setTimeout(() => {
  console.log('This will not be logged if clearTimeout is called before 2 seconds');
}, 2000);
// Cancel the scheduled task
setTimeout(() => {
}, 1000);
This code demonstrates how to cancel a setTimeout call before it executes. The clearTimeout function is called with the id returned by setTimeout, cancelling the task if the clearTimeout is triggered before the timeout period.
// Using setImmediate to schedule a task to run immediately after I/O events
setImmediate(() => {
  console.log('This is logged after any pending I/O events have been handled');
This code schedules a task to run immediately after the current event loop cycle and any pending I/O events. It's non-blocking and typically used for scheduling tasks that should be executed as soon as possible after the current operation.
// Chaining setTimeout to simulate setInterval behavior
function repeatTask() {
  console.log('This task is repeated every 2 seconds');
  setTimeout(repeatTask, 2000);
// Start the repeating task
setTimeout(repeatTask, 2000);
This code creates a chain of setTimeout calls to simulate the behavior of setInterval. A task is scheduled to run every 2 seconds by re-invoking setTimeout at the end of each task execution.