. Advertisement .
..3..
. Advertisement .
..4..
Programming in general and Node.js in particular always have situations where certain script or code needs periodic execution. That is what we call sleep, as the computer thread essentially rests while waiting for the right condition. This technique is extremely vital for many aspects of programming.
That is why we prepared this article to help you figure out how to sleep in Node.js.
Sleep In Node.js Using The setTimeout() Method
setTimeout()
is an integrated method within Node.js with the ability to allow the execution of any function of a periodic nature. There are a lot of parameters that this function accepts, but only two of them are must-haves, the rest are not necessary.
It will return an integer value with the name timeout ID, which refers to the setTimeout()
function’s created object. Here is its syntax:
setTimeout(() => {function}, time);
As you can see, we only use the two vital input parameters here. One of them is the function parameter, meaning what you want to do after each interval. The other refers to the time in milliseconds that the function will need to wait before returning to code execution.
This function works wonders when you use it in conjunction with callback functions. Its nature allows you to manipulate when the callback function will emerge with high precision.
Example:
setTimeout(() => {console.log("This is the first function")}, 2000);
setTimeout(() => {console.log("This is the second function")}, 4000);
setTimeout(() => {console.log("This is the final function")}, 5000);
Output:
This is the first function
This is the second function
This is the final function
Sometimes you can encounter the require is not defined error if you mess up the input.
Sleep In Node.js Using The setInterval() method
Node.js’s timers module features a method called setInterval()
, which has similar functionality as setTimeout()
. Unlike the latter, however, the former will keep on executing your script without stopping within the given intervals.
That is why you must always make sure to put in an explicit command to stop the script.
As with the setTimeout()
function, setInterval()
also has two vital input arguments, the time interval to execute on and the function needed to be executed. Its return value is a timer ID object, which you can use to cancel the timer itself.
As we mentioned, you need to explicitly tell the function to stop executing codes. You can either do so by pressing a combination of Ctrl and C on your keyboard or using a function called clearInterval()
.
All you need to do is pass the returned timer ID object into clearInterval()
as an input parameter.
Example:
setInterval(() => {
console.log("Function repeatedly executed after every 2 seconds!");
}, 2000)
Output:
Function repeatedly executed after every 2 seconds!
Function repeatedly executed after every 2 seconds!
Function repeatedly executed after every 2 seconds!
Function repeatedly executed after every 2 seconds!
Function repeatedly executed after every 2 seconds!
Function repeatedly executed after every 2 seconds!
^C
Sleep In Node.js Using The await() keyword.
Other programming languages like C offer a specific sleep function, letting the computer rest one particular thread while another starts. However, that is not the case with JavaScript. You do have the ability to bypass this issue by making use of an asynchronous promise-based function.
async function my_asyncFunction() {
console.log("Some Code we want to be executed");
await sleep(4000);
console.log("Some other code we want to be executed after some seconds");
}
function sleep(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
my_asyncFunction();
After creating it, you can use the await()
keyword to invoke a condition and let the thread rest while the condition isn’t fulfilled. It does have a huge issue of not working without the help of the async type of functions.
Conclusion
With this article in mind, we believe that now you won’t have any issues with figuring out how to sleep in Node.js. The setInterval()
approach is the most powerful out of the three solutions, but it’s also the hardest to manage.
You need to build a specific function for the await()
method, but it’s also the most versatile, as you can change the function according to your needs. The setTimeout()
approach is the most basic, making it the easiest to master.
Leave a comment