I want to show here how to implement wait (or delay or sleep) function but in NodeJS environment. This post is an extension of my JavaScript wait or delay functions article here on my website. I explained there in details how to build wait function in JavaScript. But here, I will provide just short examples of how to build wait function in NodeJS.
What is important to mention – in NodeJS we can by default use the most modern standard of JavaScript code (with Promise and async/await standard from ES2017+), but I created also alternative which is build with recurrent function without promises and async/await syntax.
Table of Contents
Short introduction – REST API requests with NodeJS WAIT function
In all examples below, my JavaScript NodeJS code with wait function uses external demo REST API. This returns product list (computer’s components). It’s very simple REST API.
Response from demo API looks like that:
{
"index": 1,
"price": 138,
"product": "cpu",
"owner": "MULTRON"
}
All examples which are described below you can find in our GitHub HERE. But I strongly recommend to read this article to understand how NodeJS wait functions works.
NodeJS wait function – basic example
I created in example below the easiest usage of wait function. The syntax of wait function is very easy. Let’s go through that step by step:
wait5sec()function – it containssetTimeout()function wrapped byPromise-
Promiseis resolved whensetTimeout()is done. - Next,
wait5sec()is used in parent method:callAPI()– just before API request. -
wait5sec()is triggered asASYNCfunction – it means that procedure will go further when insidewait5sec()thePromisewill be resolved bysetTimeout()execution. - Next API request is done (also as
ASYNCfunction). - Results are logged by
runWait5sec()method.
import axios from 'axios';
function wait5sec (waitTime) {
return new Promise ((resolve) => {
setTimeout(() => {
resolve(true);
}, waitTime);
});
}
async function callAPI (i) {
await wait5sec(5000); // wait function
const res = await axios(`http://localhost:8080/dev-apps/php-api/orders/${i}`);
return res.data;
}
export const runWait5sec = async () => {
const result = await callAPI(1);
console.log(result);
}The most important thing is that whenever you would like to use wait5sec() function to make waiting your NodeJS code, you must put it as ASYNC function. So it means that parent function must be also ASYNC function and AWAIT statement must be before wait5sec() function.
This code requires to run the EcmsScript 2017 standard.
Check how this code of NodeJS wait function works on film below:
NodeJS wait function – FOR loop example
This example is more real-life example usage of NodeJS wait method. Imagine situation like I had some time ago:
I was working some time ago on a small project where my NodeJS application was requesting the Open Street Map REST API for data. This is an open API, so it has limitation and it is not possible to make at once a few requests for big data sets. I needed to make every AJAX request at least 2 minutes after the previous one.
So the first example (above) we must use simply inside for loop.
We will request the demo API a few times and always our NodeJS code will need to wait 5 seconds before next request.
Mostly it works the same like in first basic example above. The key difference here is that callAPI() function is triggered in for loop a few times.
But other functionality looks the same – so wait5sec() function is a Promise with setTimeout() inside it which which resolves a Promise . This method always must be triggered as async/await.
import axios from 'axios';
export const runWait5secForLoop = async () => { // start here
for (let i = 1; i < 4; i++) { // for loop
const result = await callAPI(i); // which calls callAPI method given number times
console.log(result); // log results
}
}
async function callAPI (i) { // run wait function here. procedure will stop here for a given time!
await wait5sec(5000);
const res = await axios(`https://dev-bay.com/examples/php-api-js-wait/orders/${i}`);
return res.data;
}
function wait5sec(waitTime) { // this method is a promise which will be resolved when setTimeout invoked!
return new Promise((resolve) => {
setTimeout(() => {
console.log('wait finished');
resolve(true);
}, waitTime);
});
}
Check how this code of NodeJS wait function in for loop works on GIF film below:
This code requires to run the EcmsScript 2017 standard.
NodeJS wait function – recurrent function example
This example of wait function for NodeJS can callback() look more complex, because I used here the recurrent function. Long story short:
-
recurentLoopFuncfunction has inside thesetTimeout() - It takes as argument a
callback()function, - The
callback()function is invoked insidesetTimeout()body function. - Inside
callback()function it triggers again the same recurrent functionrecurentLoopFuncwith the same parameters. - Recurrent loops limit is controlled by IF statement and
seqCounterandcountvariables.
This example of NodeJS wait function is done in EcmaScript 5 standard, so it means that it will work even without the latest JavaScript engine in the background in NodeJS.
import axios from 'axios';
export const runWait5secInRecurentLoop = (i) => {
recurentLoopFunc(4, 5000, 1, function (i) {
return axios(`https://dev-bay.com/examples/php-api-js-wait/orders/${i}`);
});
}
function recurentLoopFunc (count, timeoutTime, seqCounter, callback) {
if (seqCounter < count) {
setTimeout(() => {
callback(seqCounter).then(function (result) {
var data = result.data;
console.log('wait finished');
console.log(data);
seqCounter++;
recurentLoopFunc(count, timeoutTime, seqCounter, callback);
});
}, timeoutTime);
}
}Check how this code of NodeJS wait function in recurrent loop works on GIF film below:
NodeJS WAIT function – summary
As you can see, creating a wait function in NodeJS is quite easy, as I explained that in 3 examples above. The best solution in my opinion is this from first and second example, so with async/await functions, because in NodeJS be default you have the latest JavaScript standard so you can use Promise and async/await wherever you want, not like in the client site JS apps in browsers.
As reminder – you can download and run my examples from our GitHub HERE. This is a normal NodeJS app. So the procedure here is normal:
- Once you download or clone the repository, just run the terminal in project’s directory and type
npm install. - After packages installation, type
npm start. - Then you will be asked by application which example you want to run like on image below:
Run example in NodeJS
This is everything, enjoy NodeJS WAIT functions in your project 🙂