Basics

Node.js Timers

Node.js Timing Functions

Node.js timers use setTimeout and setInterval for async scheduling.

Introduction to Node.js Timers

Node.js provides two primary functions for scheduling code execution at a later time: setTimeout and setInterval. These functions allow developers to execute code asynchronously, making them essential for handling operations that need to occur after a certain period or repeatedly in a non-blocking manner.

Using setTimeout

The setTimeout function is used to execute a single callback function after a specified number of milliseconds. This can be useful for delaying execution of a function or running a piece of code once after some time.

Using setInterval

The setInterval function is used to repeatedly execute a callback function at specified intervals, defined in milliseconds. This is useful for tasks that need to happen repeatedly, such as fetching data or updating a UI element.

Clearing Timers

Timers can be cleared using the clearTimeout and clearInterval functions. This is particularly useful when you want to cancel a timeout or interval that was previously set.

Practical Use Cases

  • Debouncing: Use setTimeout to delay processing of events like window resize or keypress, optimizing performance by avoiding excessive function calls.
  • Polling: Implement setInterval to regularly check for updates from a server.
  • Animations: Create animations by repeatedly updating UI elements at fixed intervals.
Previous
Process