timers

Simplified Explanation of Node.js Timers Module

What are Timers?

Timers are like digital alarm clocks that let you schedule tasks to happen at specific times in the future.

How Timers Work in Node.js

Node.js timers don't need to be "required" like other modules. Instead, you can use them directly using global functions.

Types of Timers

  • setTimeout: Schedules a function to be called after a single delay.

  • setInterval: Schedules a function to be called repeatedly at a specific interval.

  • clearTimeout: Cancels a previously scheduled timeout.

  • clearInterval: Cancels a previously scheduled interval.

Real World Examples

  • setTimeout: Display a message after a delay to simulate an asynchronous process.

setTimeout(() => {
  console.log("Message displayed after 5 seconds");
}, 5000); // 5 seconds in milliseconds
  • setInterval: Update a progress bar every second to show a running process.

let progress = 0;
const interval = setInterval(() => {
  console.log(`Progress: ${progress}%`);
  progress += 10;
  if (progress >= 100) {
    clearInterval(interval); // Stop the interval when progress reaches 100%
  }
}, 1000); // 1 second in milliseconds
  • clearTimeout: Cancel a scheduled timeout if it's no longer needed.

const timeout = setTimeout(() => {
  console.log("Timeout message");
}, 5000);

clearTimeout(timeout); // Cancel the timeout before it executes

Potential Applications

  • Asynchronous Programming: Scheduling tasks to be performed later without blocking the main thread.

  • Animations/Effects: Creating smooth UI animations by scheduling updates at specific intervals.

  • Polling: Periodically checking for external data or events.

  • Timeouts: Limiting the execution time of an operation or task.


Immediate:

Imagine you want to send a letter immediately. You can't wait for the next scheduled postal delivery. So, you use an immediate service that delivers your letter right away.

In Node.js, the Immediate object works like that. It allows you to execute an action as soon as possible, without waiting for the event loop to complete its current cycle.

Functions:

  • immediate.ref():

    This function tells the event loop to keep running even if there are no other tasks to execute. It's like saying, "Hey event loop, don't stop, keep going until my immediate action is complete."

  • immediate.unref():

    This function tells the event loop that it can stop running if there are no other tasks to execute. It's like saying, "Hey event loop, you can chill now, my immediate action will finish on its own."

Complete Implementation Example:

// Create an immediate that prints "Immediate" after 100 milliseconds
const immediate = setImmediate(() => {
  console.log("Immediate");
});

// After 0 milliseconds, call immediate.ref() to keep the event loop running
setTimeout(() => {
  immediate.ref();
}, 0);

// After 500 milliseconds, call immediate.unref() to allow the event loop to stop
setTimeout(() => {
  immediate.unref();
}, 500);

// Expected output: "Immediate"

Real-World Application:

  • High-Priority Tasks: Execute critical tasks without waiting for the event loop to complete. For example, processing a real-time event like a mouse click or keyboard input.

  • Async Callbacks: Handle asynchronous callbacks immediately after they're called, ensuring that important actions are not delayed. For example, responding to a user request or sending a notification.


immediate.hasRef()

  • Returns: {boolean}

If true, the Immediate object will keep the Node.js event loop active.

Simplified Explanation

An Immediate object represents a function that will be executed as soon as the current event loop iteration finishes. The hasRef() method checks if there are any references to the Immediate object, meaning that it is still scheduled to be executed. If there are no references, the Immediate object will be removed from the event loop and will not be executed.

Real-World Example

The following code snippet shows how to use the hasRef() method:

const immediate = setImmediate(() => {
  console.log('Hello world!');
});

console.log(immediate.hasRef()); // true

clearImmediate(immediate);

console.log(immediate.hasRef()); // false

In this example, the hasRef() method is used to check if the Immediate object is still scheduled to be executed. After the Immediate object is cleared, the hasRef() method returns false, indicating that it is no longer scheduled to be executed.

Potential Applications

The hasRef() method can be used to track the status of Immediate objects and to ensure that they are cleared when they are no longer needed. This can be useful for debugging purposes and for ensuring that the event loop is not kept active unnecessarily.


immediate.ref()

Simplified Explanation:

Imagine the Node.js event loop like a spinning wheel. When there are things to do, the wheel keeps spinning. But when there's nothing to do, it can stop spinning to save energy.

immediate.ref() tells the event loop, "Hey, keep spinning even if there's nothing else to do, because this Immediate is waiting." So, the event loop won't stop even if there are no other active tasks.

Code Snippet:

const { Immediate } = require("timers");

// Create an Immediate
const immediate = new Immediate(() => {
  console.log("Hello!");
});

// Keep the event loop spinning while Immediate is active
immediate.ref();

Real-World Example:

Suppose you have a server that listens for HTTP requests and sends responses. When a request comes in, it creates an Immediate to process it. By calling immediate.ref(), the event loop will keep spinning until the response is sent, even if there are no other requests being processed.

Potential Applications:

  • Keeping event loops active during long-running tasks

  • Preventing the event loop from stopping prematurely in asynchronous applications

  • Ensuring that critical tasks are always processed


immediate.unref()

  • What it does: Makes the Immediate object not require the Node.js event loop to stay active.

  • Return value: A reference to the Immediate object.

  • How it works:

    • Normally, the Node.js event loop keeps running until there are no more active Immediate objects.

    • If you call immediate.unref(), the event loop can exit even if there's still an active Immediate object.

    • This means the Immediate object's callback might not be called.

  • Example:

const immediate = setImmediate(() => {
  console.log("hello");
});

immediate.unref();

// The event loop may exit before this is printed:
immediate.on("complete", () => {
  console.log("completed");
});

immediate[Symbol.dispose]()

Simplified Explanation:

What it is: A method that cancels a scheduled immediate task.

How it works: Like pressing the "cancel" button on an alarm that was set to go off in the future.

Detailed Explanation:

Immediate Tasks:

  • Immediate tasks are functions that are scheduled to run as soon as possible, after the current code execution is complete.

  • They are commonly used for quick, urgent tasks that need to be done immediately, like showing an error message or updating a UI element.

Symbol.dispose() Method:

  • The immediate[Symbol.dispose()] method allows you to cancel a scheduled immediate task.

  • Calling this method is like canceling an alarm you set for a future time. It prevents the task from running.

Code Snippet:

// Schedule an immediate task to log "Hello" after 1 second
const immediateId = setImmediate(() => {
  console.log("Hello");
});

// Cancel the immediate task after 500 milliseconds
setTimeout(() => {
  immediateId[Symbol.dispose]();
}, 500);

Real-World Applications:

  • Canceling a loading spinner or progress bar if data becomes available before the timer runs out.

  • Preventing multiple XHR requests from being made if they overlap.

  • Stopping a countdown timer if the user takes a certain action.


Timers

Timers are used to schedule functions to run after a certain amount of time. Node.js has two main types of timers:

  • setTimeout() - schedules a function to run once after a specified delay.

  • setInterval() - schedules a function to run repeatedly at a specified interval.

Timeout Object

When you call setTimeout() or setInterval(), a Timeout object is returned. This object has two important methods:

  • timeout.ref() - keeps the Node.js event loop running as long as the timer is active.

  • timeout.unref() - allows the Node.js event loop to stop running even if the timer is still active.

Real World Applications

Here are some real-world applications of timers:

  • Displaying a notification after a certain amount of time.

  • Refreshing data in a web application on a regular interval.

  • Controlling the timing of animations.

Example

Here is an example of how to use setTimeout() and timeout.ref():

// Schedule a function to run after 1 second.
const timeout = setTimeout(() => {
  console.log("Hello world!");
}, 1000);

// Keep the event loop running indefinitely.
timeout.ref(); // You can remove this line to allow the event loop to stop

// After 1 second, "Hello world!" will be printed to the console.

What is timeout.close()?

timeout.close() is a method used to cancel a previously set timeout.

How does it work?

When you call setTimeout(), it returns a reference to the timeout. This reference is called a Timeout. The Timeout object has a close() method that can be used to cancel the timeout.

Why would you want to cancel a timeout?

There are several reasons why you might want to cancel a timeout:

  • You may have changed your mind about what you wanted to do with the timeout.

  • The code that the timeout was going to run may no longer be needed.

  • The timeout may be causing performance problems.

How do you use timeout.close()?

To cancel a timeout, you simply call the close() method on the Timeout object. For example:

const timeout = setTimeout(() => {
  console.log('Hello world!');
}, 1000);

timeout.close();

This code will cancel the timeout and prevent the message from being logged to the console.

Real-world examples

Here are a few real-world examples of how timeout.close() can be used:

  • To cancel a timeout that is no longer needed. For example, if you have a timeout that is set to run a function after a certain amount of time, but the function is no longer needed, you can cancel the timeout to prevent it from running.

  • To cancel a timeout that is causing performance problems. For example, if you have a timeout that is set to run a function every second, but the function is causing performance problems, you can cancel the timeout to improve performance.

  • To change the behavior of a timeout. For example, if you have a timeout that is set to run a function after a certain amount of time, but you want to change the amount of time before the function runs, you can cancel the timeout and set a new one with the new time.

Additional notes

  • timeout.close() is a legacy method and should not be used in new code. Instead, use clearTimeout() to cancel a timeout.

  • timeout.close() does not actually remove the timeout from the system. It simply prevents the timeout from running.

  • timeout.close() can be called multiple times. However, only the first call will have any effect.


timeout.hasRef()

Simplified Explanation:

Imagine the event loop in your Node.js application as a party. When you create a Timeout, it's like inviting a new guest to the party. If the Timeout has a reference (or "hasRef"), it means the guest has a drink in their hand, keeping the party going.

Detailed Explanation:

The hasRef() method checks if the Timeout object is keeping the Node.js event loop active. Here's what happens behind the scenes:

  • By default, when you create a Timeout, it's assigned a reference count of 0.

  • When the Timeout fires, its reference count is decremented by 1.

  • If the reference count becomes 0, the Timeout is automatically removed from the event loop, and the event loop can quit.

  • However, if the Timeout has a reference (e.g., it's assigned to a variable somewhere in your code), the reference count won't drop to 0, and the Timeout will keep the event loop active.

Code Sample:

// Create a timeout with a reference
const timeout = setTimeout(() => {
  console.log("Hello, world!");
}, 1000);

// Check if the timeout has a reference
console.log(timeout.hasRef()); // true

Real-World Applications:

  • Keeping the server alive: A web server can use Timeout objects to keep itself active, even if there are no incoming requests. This ensures that the server is always ready to respond to new requests.

  • Delayed processing: You can use Timeout objects to schedule tasks to run after a specific delay. For example, you could use a Timeout to send an email reminder to a user 24 hours after they sign up for your service.


timeout.ref()

Explanation:

Imagine a party where the lights go out if there are no guests left.

In Node.js, the event loop is like the party lights. It keeps running as long as there is something to do, like running code.

A Timeout is like a guest who is supposed to leave the party after a certain time.

By default, Timeout guests are "ref'ed", which means they tell the party lights to stay on even if they leave.

But if you call timeout.unref(), it's like the guest saying "Don't wait for me, I'm leaving and I won't be back."

If you then call timeout.ref() again, it's like the guest coming back to the party and saying "Oops, sorry, I'm staying after all."

Simplified Version:

When you create a Timeout, it tells the event loop to stay on even after it's finished running its code.

If you call timeout.unref(), it tells the event loop to ignore the timeout and exit when it's done.

Calling timeout.ref() again after timeout.unref() is like changing your mind and telling the event loop to wait for the timeout again.

Code Snippet:

const timeout = setTimeout(() => {
  console.log("Hello!");
}, 1000);

// Tell the event loop to exit when the timeout is done
timeout.unref();

// Change our minds and tell the event loop to wait
timeout.ref();

Real-World Use:

  • Long-running processes: If you have a process that takes a long time to run, but you don't need to wait for it, you can unref() it to allow the event loop to exit and process other tasks.

  • HTTP requests: If you make an HTTP request and don't need to wait for the response, you can unref() the request to allow the event loop to exit while the request is being processed.


What is timeout.refresh()?

timeout.refresh() is a method in Node.js that allows you to reset the timer for a specific timeout object. This means you can change when the timer will expire without creating a new one.

How does timeout.refresh() work?

When you call timeout.refresh(), it does two things:

  1. It resets the timer's start time to the current time.

  2. It reschedules the timer to call its callback at the previously specified duration, adjusted to the new start time.

Why would you use timeout.refresh()?

You might use timeout.refresh() if you want to:

  • Extend the duration of a timer without creating a new one.

  • Reset the timer to a specific point in time.

  • Update the timer's callback function.

Example:

const setTimeout = require("timers").setTimeout;
const timeout = setTimeout(() => {
  console.log("Hello, world!");
}, 1000); // Set a timeout for 1000 milliseconds

// Reset the timeout to 2000 milliseconds
timeout.refresh(2000);

Real-world application:

One real-world application of timeout.refresh() is in creating a countdown timer. You could create a timer that starts at a specific time and counts down to zero. When the timer reaches zero, it could trigger an action, such as sending an email or playing a sound.

Potential applications:

  • Creating animations that start and stop at specific times.

  • Scheduling tasks to run at regular intervals.

  • Implementing countdown timers.

  • Resetting timeouts based on user input or other events.


timeout.unref()

Simplified Explanation:

When you create a timeout, Node.js keeps the event loop running until the timeout is triggered. This means even if there are no other tasks to do, the process won't exit.

If you don't care if the process exits before the timeout happens, you can use timeout.unref() to tell Node.js that it doesn't need to keep the event loop running for this timeout.

Code Example:

const timeout = setTimeout(() => {
  console.log("This will never be executed");
}, 1000);

timeout.unref();

Real-World Application:

This is useful for tasks that don't need to complete before the program exits. For example, you could use timeout.unref() for tasks that log errors or send notifications.


Symbol.toPrimitive()

Let's say you have a timeout that you created like this:

const timeout = setTimeout(() => {
  console.log("Hello world!");
}, 1000);

This timeout will cause the message "Hello world!" to be printed to the console after 1 second.

But what if you want to cancel this timeout before it runs? You can do this by calling the clearTimeout() function with the primitive value of the timeout.

The primitive value is a number that is unique to each timeout. You can get the primitive value by calling the Symbol.toPrimitive() method on the timeout.

console.log(timeout[Symbol.toPrimitive]()); // 1

This will print the number 1 to the console. This number is the primitive value of the timeout.

You can use this number to clear the timeout with the clearTimeout() function:

clearTimeout(timeout[Symbol.toPrimitive]());

This will cancel the timeout and prevent the message "Hello world!" from being printed to the console.

Real-world applications

Timeouts are used in a variety of applications, such as:

  • Delaying the execution of code: You can use a timeout to delay the execution of code until a certain amount of time has passed. This can be useful for things like waiting for a response from a server or for displaying a loading animation.

  • Polling: You can use a timeout to periodically check for a condition. This can be useful for things like checking for new messages or for checking if a file has been downloaded.

  • Debouncing: You can use a timeout to debounce events. This means that you can prevent an event from being executed multiple times in a short period of time. This can be useful for things like preventing multiple button clicks from submitting a form.


timeout[Symbol.dispose]()

Simplified Explanation:

What it does: Stops the timeout from executing.

How it works: When you create a timeout using setTimeout() or setInterval(), it creates a timer that will run a function after a specified delay. timeout[Symbol.dispose]() stops that timer, preventing the function from running.

Code Example:

const timeout = setTimeout(() => {
  console.log("Hello, world!");
}, 1000);

// Stop the timeout before it executes
timeout[Symbol.dispose]();

Real-World Application:

  • To prevent a function from running if certain conditions are met.

  • To cancel a timeout if it's no longer needed.

Additional Notes:

  • Symbol.dispose is an ES6 symbol (a special identifier).

  • It's not available in older versions of Node.js, so you may need to use timeout.unref() instead.


Timers in Node.js

Timers in Node.js are a way to schedule a function to be called after a certain amount of time. There are three main types of timers:

  • setTimeout

  • setInterval

  • setImmediate

setTimeout

setTimeout is used to schedule a function to be called once, after a specified delay. The syntax is:

setTimeout(callback, delay, ...args)

where:

  • callback is the function to be called

  • delay is the delay in milliseconds

  • ...args are any additional arguments to pass to the callback function

For example, the following code will log "Hello world!" to the console after a delay of 2 seconds:

setTimeout(() => {
  console.log("Hello world!");
}, 2000);

setInterval

setInterval is used to schedule a function to be called repeatedly, at a specified interval. The syntax is:

setInterval(callback, interval, ...args)

where:

  • callback is the function to be called

  • interval is the interval in milliseconds

  • ...args are any additional arguments to pass to the callback function

For example, the following code will log "Hello world!" to the console every 2 seconds:

setInterval(() => {
  console.log("Hello world!");
}, 2000);

setImmediate

setImmediate is used to schedule a function to be called as soon as possible, after the current event loop iteration has completed. The syntax is:

setImmediate(callback, ...args)

where:

  • callback is the function to be called

  • ...args are any additional arguments to pass to the callback function

For example, the following code will log "Hello world!" to the console as soon as possible, after the current event loop iteration has completed:

setImmediate(() => {
  console.log("Hello world!");
});

Real-world examples

Timers are used in a variety of real-world applications, including:

  • Scheduling tasks to run at a specific time

  • Polling for data from a server

  • Animating user interfaces

  • Debouncing and throttling user input

Potential applications

Some potential applications for timers include:

  • Scheduling a task to run every day at midnight

  • Polling for new data from a server every 5 minutes

  • Animating a progress bar

  • Debouncing a search input field


Simpler Explanation of setImmediate(callback[, ...args])

What is setImmediate()?

Imagine a to-do list in Node.js. Normally, things on the list are handled in order, like a line at the grocery store. But setImmediate() is like a special express lane for urgent tasks.

How does it work?

When you call setImmediate(), it puts a new task at the very FRONT of the to-do list. This means that your urgent task will be handled as soon as possible, before any other tasks on the list.

What can I use it for?

Here's a common example:

Code Example:

// Log a message right away using `setImmediate()`.
setImmediate(() => {
  console.log("Hello, world!");
});

// Log a message after a short delay.
setTimeout(() => {
  console.log("Hello, again!");
}, 1000); // 1 second delay

Output:

Hello, world!
Hello, again!

In this example, the setImmediate() task is handled first, even though it came after the setTimeout() task. This is because setImmediate() is like an express lane for urgent tasks.

Real-World Applications:

  • UI responsiveness: Keeping your user interface responsive by handling urgent tasks immediately.

  • Database transactions: Committing critical database operations immediately to ensure data integrity.

  • Error handling: Triggering immediate actions to handle errors and prevent further damage.

  • WebSocket communication: Responding to incoming WebSocket events without waiting for other tasks to finish.


setInterval()

Usage:

setInterval(() => {
  // Do something every `delay` milliseconds
}, delay);

Parameters:

  • callback: The function to run every delay milliseconds. Use an arrow function to avoid the need for bind().

  • delay: The time in milliseconds between each call to callback. Defaults to 1 millisecond.

Return Value:

  • A Timeout object that you can use to cancel the interval with clearInterval().

Explanation:

setInterval() sets up a timer that calls your callback function every delay milliseconds. This is useful for creating animations, tracking time, or polling for new data.

Real-World Example:

Suppose you want to create a simple clock that updates every second. You can use setInterval() as follows:

const clock = setInterval(() => {
  // Get the current time
  const now = new Date();

  // Update the clock display
  document.getElementById("clock").innerHTML = now.toLocaleTimeString();
}, 1000); // 1000 milliseconds = 1 second

Potential Applications:

  • Creating animations

  • Tracking time

  • Polling for new data

  • Simulating real-world events

clearInterval()

Usage:

clearInterval(timeout);

Parameters:

  • timeout: The Timeout object returned by setInterval().

Explanation:

clearInterval() cancels the interval timer set up by setInterval(). This is useful when you no longer need the timer to run.

Real-World Example:

In the clock example above, you can cancel the timer when the user closes the page:

window.addEventListener("beforeunload", () => {
  clearInterval(clock);
});

Potential Applications:

  • Stopping animations

  • Cancelling timed events

  • Cleaning up resources


setTimeout() Method in Node.js

The setTimeout() method in Node.js is used to schedule a callback function to be executed after a specified delay.

Syntax

setTimeout(callback[, delay[, ...args]])

Parameters

  • callback: The function to be executed after the delay.

  • delay (optional): The number of milliseconds to wait before executing the callback. Defaults to 1.

  • ...args (optional): Additional arguments to be passed to the callback function.

Return Value

A Timeout object that can be used to cancel the timeout.

Simplified Explanation

Imagine you want to set an alarm to go off in 5 minutes. You would use setTimeout() like this:

setTimeout(() => {
  console.log("Alarm!");
}, 5 * 60 * 1000); // Delay in milliseconds

This would schedule a callback function to be executed after 5 minutes, which would then log "Alarm!" to the console.

Real-World Example

One common use case for setTimeout() is to implement a debounce function. Debouncing is a technique used to prevent a function from being called too often, such as when a user is typing into a search bar.

Here's how you could implement a debounce function using setTimeout():

let timeoutId;

function debounce(callback, delay) {
  clearTimeout(timeoutId); // Clear any existing timeout
  timeoutId = setTimeout(callback, delay); // Schedule a new timeout
}

This function takes a callback function and a delay, and it schedules the callback to be executed after the delay. However, if the function is called again before the delay has passed, the existing timeout is cleared and a new timeout is scheduled. This ensures that the callback is only executed once after the user stops typing.

Potential Applications

setTimeout() has numerous applications in real-world scenarios:

  • Delayed execution: Scheduling tasks to run at a specific time in the future.

  • Debouncing: Preventing functions from being called too often.

  • Polling: Periodically checking for updates by scheduling a callback to run repeatedly.

  • Rate limiting: Controlling the number of requests or tasks that can be executed within a given time period.


Cancelling Timers in Node.js

What are Timers?

Timers are like alarms that tell your code to do something at a specific time. Node.js has three main types of timers:

  • setImmediate() - Runs a function right away, ahead of other scheduled tasks.

  • setInterval() - Repeats a function at regular intervals.

  • setTimeout() - Runs a function after a specified delay.

Cancelling Timers

You can cancel a timer using the object it returns when you create it.

For setImmediate(), setInterval(), and setTimeout():

const timer = setTimeout(() => {
  // Do something
}, 1000);

// Cancel the timer
clearTimeout(timer);

For promisified setImmediate() and setTimeout():

const {
  setImmediate: setImmediatePromise,
  setTimeout: setTimeoutPromise,
} = require("node:timers/promises");

const ac = new AbortController();
const signal = ac.signal;

setImmediatePromise("foobar", { signal })
  .then(console.log)
  .catch((err) => {
    if (err.name === "AbortError") console.error("The immediate was aborted");
  });

// Cancel the timer
ac.abort();

Real-World Examples

Using setImmediate() to prioritize tasks:

const fs = require("fs");

// Read a file right away, before other tasks
setImmediate(() => {
  fs.readFile("data.txt", "utf8", (err, data) => {
    if (err) throw err;
    console.log(data);
  });
});

// Other tasks will run after the file is read

Using setInterval() to check for updates:

const pollingInterval = 1000; // Check every second

// Check for updates every second
setInterval(() => {
  // Check for new data or changes
}, pollingInterval);

Using setTimeout() to delay a task:

const delay = 2000; // Delay by 2 seconds

// Run the function after a 2-second delay
setTimeout(() => {
  // Do something
}, delay);

clearImmediate(immediate)

  • immediate {Immediate} An Immediate object as returned by [setImmediate()][].

Cancels an Immediate object created by [setImmediate()][].

Simplified Explanation:

clearImmediate() is used to cancel a pending immediate execution. Immediate executions are scheduled using [setImmediate()][]. When you call clearImmediate(), the scheduled immediate execution is removed from the queue and will no longer be executed.

Real-World Example:

Let's say you have a function that you want to execute immediately, but you also want to have the option to cancel it if certain conditions are not met. You can achieve this by using setImmediate() and clearImmediate():

function myFunction() {
  // Do something
}

const immediateId = setImmediate(myFunction);

// Check if certain conditions are met
if (conditionsMet) {
  // Execute the immediate function
} else {
  // Cancel the immediate function
  clearImmediate(immediateId);
}

clearInterval(timeout)

The clearInterval(timeout) method in timers cancels a Timeout object created by setInterval(). This means that the function passed to setInterval() will no longer be called.

Parameters:

  • timeout {Timeout|string|number} A Timeout object as returned by setInterval() or the primitive of the Timeout object as a string or a number.

Example:

const timeout = setInterval(() => {
  // This function will be called every second
}, 1000);

// After 5 seconds, cancel the timeout
setTimeout(() => {
  clearInterval(timeout);
}, 5000);

Applications:

clearInterval() is useful for any situation where you want to stop a function from being called at a regular interval. For example, you could use clearInterval() to stop a function that is updating a progress bar or to stop a function that is polling a server for new data.


clearTimeout()

The clearTimeout() function cancels a timer set by setTimeout().

Syntax

clearTimeout(timeout: Timeout | string | number): void;

Parameters

  • timeout: The timer to cancel. This can be either a Timeout object, a string representing the timer's ID, or a number representing the timer's ID.

Example

const timeout = setTimeout(() => {
  console.log("This will never be logged");
}, 1000);

clearTimeout(timeout); // Cancel the timer

Real World Applications

  • Canceling an animation that is no longer needed

  • Stopping a countdown timer when the user takes a certain action

  • Preventing multiple instances of a function from being executed when a user clicks a button rapidly


Timers Promises API

This API provides a modern way to use timers in Node.js by returning Promise objects instead of calling callbacks. It makes it easier to handle asynchronous code and improve readability.

Functions:

  • setTimeout(ms, value): Schedules a single-shot timer that resolves after ms milliseconds with the provided value.

  • setImmediate(value): Schedules a function to be executed "immediately" (after the current event loop cycle completes) with the provided value.

  • setInterval(ms, value): Schedules a repeating timer that calls the provided value every ms milliseconds.

Usage:

// Import the API
import { setTimeout, setImmediate, setInterval } from "timers/promises";

// Schedule a timer
const promise = setTimeout(1000, "Hello World");

// Wait for the timer to resolve
const result = await promise; // Output: 'Hello World'

Real-World Applications:

  • Delayed Actions: Scheduling a task to run after a specific time, like sending an email after 5 minutes.

  • Event Handling: Using setImmediate to handle events that should be processed immediately, such as handling user input.

  • Periodic Tasks: Scheduling recurring tasks, like fetching data from a remote server every 15 minutes.

Code Implementations:

Sending an Email with Delay:

import { setTimeout } from "timers/promises";
import { sendEmail } from "./mail.service.js";

// Send an email after 2 minutes
setTimeout(2 * 60 * 1000).then(() =>
  sendEmail("to@example.com", "Hello from Node")
);

Handling User Input:

import { setImmediate } from "timers/promises";

const readline = require("readline").createInterface({
  input: process.stdin,
  output: process.stdout,
});

readline.question("What is your name? ", (name) => {
  setImmediate(() => {
    console.log(`Nice to meet you, ${name}!`);
  });
});

Fetching Data Periodically:

import { setInterval } from "timers/promises";
import { fetchData } from "./data.service.js";

// Fetch data every 15 minutes
const interval = setInterval(15 * 60 * 1000);

interval.then(() => {
  fetchData().then((data) => {
    console.log(data);
  });
});

Benefits:

  • Cleaner and more readable asynchronous code

  • Easier error handling with try/catch blocks

  • Supports modern JavaScript features like async/await


Simplified Explanation of setTimeout Function

setTimeout is a function in Node.js that delays the execution of a function or code block for a specified amount of time. It takes three arguments:

  1. delay: The time in milliseconds to wait before executing the function.

  2. function: The function or code block to execute.

  3. arguments (optional): Arguments to pass to the function.

Example:

setTimeout(() => {
  console.log("Hello world!");
}, 1000); // Delay execution for 1000 milliseconds (1 second)

Advanced Options for setTimeout:

setTimeout also allows you to pass an object with advanced options:

  • ref: Set to false to indicate that the scheduled timeout should not require the Node.js event loop to remain active.

  • signal: An optional AbortSignal that can be used to cancel the scheduled timeout.

Potential Applications:

  • Displaying notifications after a delay

  • Executing periodic tasks

  • Delaying the execution of code until certain conditions are met

  • Canceling scheduled tasks based on user input or signal

Real-World Example:

Displaying a notification after 5 seconds:

const notification = "Your order is ready!";

setTimeout(() => {
  alert(notification);
}, 5000); // Delay execution for 5000 milliseconds (5 seconds)

Executing a task every 10 seconds:

setInterval(() => {
  console.log("Doing something...");
}, 10000); // Execute the task every 10000 milliseconds (10 seconds)

Canceling a scheduled task:

const timeoutId = setTimeout(() => {
  console.log("Task not executed");
}, 5000);

// Create an AbortController to control the timeout
const controller = new AbortController();

// Cancel the timeout if the user clicks a button
const cancelButton = document.getElementById("cancel-button");
cancelButton.addEventListener("click", () => {
  controller.abort();
  clearTimeout(timeoutId);
});

timersPromises.setImmediate([value[, options]])

What is it?

setImmediate() is a function that schedules a function to be executed in the next available tick of the event loop, after any currently pending I/O events have been processed. It returns a promise that resolves to the value passed to the function.

How do I use it?

The basic syntax of setImmediate() is:

setImmediate(callback[, arg1, arg2, ...])

where:

  • callback is the function to be executed.

  • arg1, arg2, ... are optional arguments to be passed to the callback.

You can also use the timersPromises.setImmediate() function to schedule a function to be executed in the next available tick of the event loop, but this function returns a promise that resolves to the value passed to the function.

The basic syntax of timersPromises.setImmediate() is:

setImmediate(value[, options])

where:

  • value is the value to be resolved by the promise.

  • options is an optional object that can contain the following properties:

    • ref: A boolean value that indicates whether the scheduled Immediate should require the Node.js event loop to remain active.

    • signal: An optional AbortSignal that can be used to cancel the scheduled Immediate.

Example:

The following example shows how to use setImmediate() to schedule a function to be executed in the next available tick of the event loop:

setImmediate(() => {
  console.log('Hello world!');
});

The following example shows how to use timersPromises.setImmediate() to schedule a function to be executed in the next available tick of the event loop and return a promise:

setImmediate('Hello world!').then((res) => {
  console.log(res); // Prints 'Hello world!'
});

Real-world applications:

setImmediate() can be used to defer the execution of a function until the next tick of the event loop. This can be useful for avoiding blocking the event loop, which can lead to performance issues.

For example, the following code uses setImmediate() to defer the execution of a function that logs a message to the console:

const fs = require('fs');

fs.readFile('file.txt', 'utf8', (err, data) => {
  if (err) throw err;

  setImmediate(() => {
    console.log(data);
  });
});

This code will log the contents of the file to the console in the next available tick of the event loop, after the file has been read. This prevents the event loop from being blocked while the file is being read.


Timers Promises

Timers Promises provide a way to schedule asynchronous tasks in Node.js. They are similar to the standard setTimeout() and setInterval() functions, but they return a Promise instead of a Timeout or Interval object. This makes it easier to use them in asynchronous code.

setInterval([delay[, value[, options]]])

The setInterval() method creates a Promise that generates values in an interval of delay milliseconds. The Promise will be resolved with the value passed to the second argument, or undefined if no value is provided.

The options object can be used to control the behavior of the interval. The following properties are supported:

  • ref: Set to false to indicate that the scheduled Timeout between iterations should not require the Node.js event loop to remain active.

  • signal: An optional AbortSignal that can be used to cancel the scheduled Timeout between operations.

Simplified Example

// Create an interval that generates values every 100 milliseconds
const interval = setInterval(100, "hello");

// Iterate over the interval and log the values
for await (const value of interval) {
  console.log(value);
}

Output:

hello
hello
hello
...

Real-World Application

setInterval() can be used to implement a variety of tasks, such as:

  • Polling a server for new data

  • Updating a UI element on a regular basis

  • Animating a graphic

Improved Code Snippet

The following code snippet uses the ref and signal options to control the behavior of the interval:

// Create an interval that generates values every 100 milliseconds, but does not require the event loop to remain active
const interval = setInterval(100, "hello", { ref: false });

// Create an AbortSignal to cancel the interval after 1 second
const signal = new AbortSignal();
setTimeout(() => signal.abort(), 1000);

// Iterate over the interval until the AbortSignal is triggered
try {
  for await (const value of interval) {
    console.log(value);
  }
} catch (error) {
  console.error(error);
}

timersPromises.scheduler.wait(delay[, options])

  • This is an experimental feature, so it may change in the future.

Parameters

  • delay: The number of milliseconds to wait before resolving the promise.

  • options: An optional object that can contain the following properties:

    • signal: An optional AbortSignal that can be used to cancel waiting.

Return value

  • A promise that resolves after the specified delay.

Usage

import { scheduler } from "node:timers/promises";

await scheduler.wait(1000); // Wait one second before continuing

timersPromises.scheduler.yield()

Imagine your computer as a playground with a bunch of kids running around (tasks). There are two ways to ask a kid (task) to do something:

  1. "Hey kid, come back and do this task later!" (This is like setTimeout)

  2. "Hey kid, do this task right now!" (This is like setImmediate)

timersPromises.scheduler.yield() is like asking a kid to do something right now, but instead of interrupting whatever they're currently doing, you politely say "Excuse me, can you please stop what you're doing and help me with this?"

This is useful when you have a task that needs to be done immediately, but you don't want to interrupt another task that's already running.

Real-world examples:

  • Handling user input in a web application

  • Updating the UI in a game