Node.js Timers Module

Java FileNode.js Built-in Modules


Node.js'stimersThe module provides a series of functions for executing code after a specified time or at specified intervals repeatedly. These features are very useful for implementing delayed execution, periodic tasks, and timeout control.

Althoughtimersthe module is a core module of Node.js, but its methods such assetTimeout(), setInterval()andsetImmediate()are globally available without explicit import.


Main Timer Functions

setTimeout()

setTimeout()The function is used to execute a callback function once after a specified number of milliseconds.

Example

// Print message after 2 seconds
setTimeout(() => {
  console.log('This message will be displayed after 2 seconds');
}, 2000);

Parameter Description

  1. Callback function: The function to execute
  2. Delay time: Time in milliseconds (1000 ms = 1 second)
  3. Optional parameters: Additional parameters passed to the callback function

Example

// Example with extra parameters
setTimeout((name, age) => {
  console.log(`Hello, ${name}, you are ${age}years old`);
}, 1000, 'Zhang San', 25);

clearTimeout()

clearTimeout()Used to cancel a previously setsetTimeout()timer.

Example

const timerId = setTimeout(() => {
  console.log('This message will not be displayed');
}, 2000);

clearTimeout(timerId); // Cancel the timer

setInterval()

setInterval()The function is used to repeatedly execute a callback function at specified millisecond intervals.

Example

// Print a message every 1 second
let counter = 0;
const intervalId = setInterval(() => {
  counter++;
  console.log(`This is the ${counter}execution`);
  if (counter === 5) {
    clearInterval(intervalId); // Stop the timer
  }
}, 1000);

clearInterval()

clearInterval()Used to stop a previously setsetInterval()repeating timer.

Example

const intervalId = setInterval(() => {
  console.log('This message will be displayed repeatedly');
}, 1000);

// Stop the timer after 5 seconds
setTimeout(() => {
  clearInterval(intervalId);
}, 5000);

setImmediate()

setImmediate()The function is used to execute a callback function at the end of the current event loop.

Example

console.log('Start');

setImmediate(() => {
  console.log('Callback executed immediately');
});

console.log('End');

// Output order:
// Start
// End
// Callback executed immediately

clearImmediate()

clearImmediate()Used to cancel a previously setsetImmediate()immediate callback.

Example

const immediateId = setImmediate(() => {
  console.log('This message will not be displayed');
});

clearImmediate(immediateId);

Execution Order of Timers

Understanding the Node.js event loop is very important for mastering the execution order of timers. The following is the execution order of several timers:

  1. Synchronous code: Executed first
  2. process.nextTick(): Executed immediately after the current phase ends
  3. Promise callbacks: Microtask queue
  4. setImmediate(): Executed after I/O callbacks
  5. setTimeout() and setInterval(): Executed in the check phase

Example

console.log('Start');

setTimeout(() => console.log('setTimeout'), 0);
setImmediate(() => console.log('setImmediate'));
process.nextTick(() => console.log('nextTick'));
Promise.resolve().then(() => console.log('Promise'));

console.log('End');

// Typical output order:
// Start
// End
// nextTick
// Promise
// setTimeout
// setImmediate

Advanced Usage and Notes

Canceling Timers

All timer functions return anTimeoutobject, which can be used to cancel the timer. It is safe to call the cancel function even if the timer has already executed.

Example

const timeout = setTimeout(() => {}, 1000);
clearTimeout(timeout); // Safe to call even if the timer has executed

Timer Accuracy

Node.js timers do not guarantee precise execution time; they represent a minimum waiting time. System load and other factors may affect the actual execution time.

Memory Leaks

Forgetting to clearsetInterval()timers is a common source of memory leaks. Make sure to clear timers when they are no longer needed.

Example

// Wrong approach - may cause memory leak
setInterval(() => {
  // Perform some operation
}, 1000);

// Correct approach - clear the timer at an appropriate time
const interval = setInterval(() => {
  // Perform some operation
  if (someCondition) {
    clearInterval(interval);
  }
}, 1000);

Recursive setTimeout Instead of setInterval

For tasks that require a fixed interval but have uncertain execution time each time, using recursivesetTimeoutComparesetIntervalis more reliable.

Example

function doSomething() {
  console.log('Executing task...');
 
  // Simulate uncertain task execution time
  const delay = Math.random() * 1000;
 
  setTimeout(doSomething, 1000 + delay);
}

setTimeout(doSomething, 1000);

Practical Application Examples

Implementing a Simple Countdown

Example

function countdown(seconds) {
  let current = seconds;
 
  console.log(`Countdown starts: ${current}seconds`);
 
  const timer = setInterval(() => {
    current--;
   
    if (current <= 0) {
      clearInterval(timer);
      console.log('Countdown ended!');
    } else {
      console.log(`Remaining time: ${current}seconds`);
    }
  }, 1000);
}

countdown(5);

Request Timeout Handling

Example

function fetchWithTimeout(url, timeout = 5000) {
  return new Promise((resolve, reject) => {
    const timeoutId = setTimeout(() => {
      reject(new Error(`Request timeout (${timeout}ms)`));
    }, timeout);
   
    fetch(url)
      .then(response => {
        clearTimeout(timeoutId);
        resolve(response);
      })
      .catch(error => {
        clearTimeout(timeoutId);
        reject(error);
      });
  });
}

// Usage example
fetchWithTimeout('https://api.example.com/data')
  .then(data => console.log(data))
  .catch(error => console.error(error));

By mastering Node.js'stimersmodule, you can effectively control the execution timing of code and implement various scheduled tasks and asynchronous control flows.

Java FileNode.js Built-in Modules

Other Extensions