Introducci贸n a Node.js
Introducci贸n Node.js
Instalaci贸n y configuraci贸n del entorno de Node.js
Primer proyecto con Node.js
Quiz: Introducci贸n a Node.js
M贸dulos y gesti贸n de paquetes
Tipos de M贸dulos en Node.js
Gesti贸n de Paquetes con NPM
Creaci贸n de un Paquetes con NPM
Publicaci贸n de Paquetes con NPM
Quiz: M贸dulos y gesti贸n de paquetes
M贸dulos nativos en Node.js
Introducci贸n al M贸dulo FS de Node.js
Leer y escribir archivos en Node.js
M贸dulo fs: Implementar transcripci贸n de audio con OpenAI
M贸dulo Console: info, warn, error, table
M贸dulo Console: group, assert, clear, trace
M贸dulo OS: informaci贸n del sistema operativo en Node.js
M贸dulo Crypto: cifrado y seguridad en Node.js
M贸dulo Process: manejo de procesos en Node.js
Timers: setTimeout, setInterval en Node.js
Streams: manejo de datos en tiempo real en Node.js
Buffers: manipulaci贸n de datos binarios en Node.js
Quiz: M贸dulos nativos en Node.js
Servidores con Node.js
HTTP: fundamentos de servidores en Node.js
Servidor nativo y streaming de video en Node.js
You don't have access to this class
Keep learning! Join and start boosting your career
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.
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());
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.
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.
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.
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.
Timers have numerous practical applications in Node.js development:
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
Want to see more contributions, questions and answers from the community?