You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesi贸n a prueba de IA

Antes: $249

Currency
$209
Suscr铆bete

Termina en:

0 D铆as
5 Hrs
17 Min
52 Seg
Curso de Fundamentos de Node.js

Curso de Fundamentos de Node.js

Oscar Barajas Tavares

Oscar Barajas Tavares

Timers: setTimeout, setInterval en Node.js

16/20
Resources

Asynchronous programming is one of the fundamental pillars of Node.js, allowing us to create efficient applications that do not block the main thread of execution. The timers module provides essential tools to control the flow of time in our applications, offering functionalities that go beyond what we find in the browser. By mastering these functions, you will be able to create more robust and better performing applications.

What is the timers module in Node.js?

The timers module in Node.js provides a global API that allows us to schedule functions to run at specific times. Although some of these functions such as setTimeout or setInterval are familiar to those who have worked with JavaScript in the browser, in Node.js they have particular features that make them especially useful within the Node runtime environment.

To better understand how these timers work, let's create a file called timers.js and explore the different functions available:

// We mark the current time to watch the execution flowconsole.log("Current time", new Date().toLocaleTimeString());
// setTimeout - executes code after a specified time (one time only)const timeout = setTimeout((() => { console.log("This message appears after two seconds");}, 2000);
// setImmediate - executes code at the next iteration of the event loopsetImmediate(() => { console.log("This message appears at the next interaction of the loop");});
// setInterval - executes code repeatedly with a time intervalconst intervalID = setInterval(() => { console.log("This message appears every three seconds");}, 3000);
// Cancel interval after 10 secondssetTimeout((() => { console.log("Cancel interval after ten seconds"); clearInterval(intervalID);}, 10000);
// Create a timeout that will never run because we cancel it immediatelyconst timeOutID = setTimeout(() => { console.log("This message will never appear");}, 10000);clearTimeout(timeOutID);
console.log("End time", new Date().toLocaleTimeString());

How does setTimeout work in Node.js?

setTimeout is a function that allows us to execute code after a specific time (in milliseconds). This function executes the code only once and is perfect for tasks that need to be delayed:

setTimeout(() => { console.log("This message appears after two seconds");}, 2000);

In this example, the message will be displayed exactly 2 seconds after the function has been logged. It is important to note that the code continues to execute while waiting for the timer time to expire.

What does setImmediate do and when to use it?

setImmediate is a Node.js-specific function that executes code on the next iteration of the event loop:

setImmediate(() => { console.log("This message appears on the next interaction of the loop");});

This function is useful when you need something to run as soon as possible, but after the current code has finished executing. It is faster than setTimeout(fn, 0) and is optimized for the Node.js environment.

How to manage recurring tasks with setInterval?

When we need to execute code repeatedly at regular intervals, setInterval is the right tool:

const intervalID = setInterval(() => { console.log("This message appears every three seconds");}, 3000);

This function will execute the provided code every 3 seconds indefinitely, until the program terminates or until we cancel the interval manually.

How to cancel timers in Node.js?

It is essential to know how to stop timers when we no longer need them, especially to avoid memory leaks in long-running applications:

// To cancel an intervalclearInterval(intervalID);
// To cancel a timeoutclearTimeout(timeOutID);

In order to cancel a timer, we need to save its ID when we create it. This ID is the return value of the setTimeout and setInterval functions.

What are the practical use cases for timers?

Timers have numerous practical applications in Node.js development:

  • Scheduled notifications: sending reminders or alerts after a specified time.
  • Resource polling: Periodically check the status of an external resource.
  • Resource cleaning: Schedule maintenance tasks to run at specific times.
  • Automatic retries: Implement retry logic with exponential waits.
  • Animations or UI updates: In applications that use Node.js for server rendering.

An interesting example is how we can use timers to implement a notification system:

function sendNotification(message, recipient) { console.log(`Sending"${message}" to ${recipient}`); // Actual sending logic....
}
const notificationID = setTimeout(() => { sendNotification("Your order has been processed", "[email protected]");}, 5000);
// If something fails before, we can cancel the notificationfunction cancelProcess() { console.log("Process failed, canceling notification"); clearTimeout(notificationID);}

Proper handling of timers in Node.js allows you to create more efficient and responsive applications. These mechanisms are essential for working with asynchronous operations and managing the flow of time in your applications. Have you ever used these timers in your projects? Share in the comments how you have implemented them and what challenges you have encountered.

Contributions 1

Questions 0

Sort by:

Want to see more contributions, questions and answers from the community?

Si ya aprendimos que hay un console.time, porque no usarlo? ```js console.time('timeout'); setTimeout(() => { console.log('Timeout body message'); console.timeEnd('timeout'); }, 2000); ```console.time('timeout'); setTimeout(() => {聽 聽 console.log('Timeout body message');聽 聽 console.timeEnd('timeout');}, 2000);