Delay execution in Node.js

In this tutorial, we will learn to cause delays in our program. The delay means we want to execute our function after a particular period. For this, we can try either of these two approaches- the setTimeout() function or async/await.

Delaying the execution in Node.js

Using setTimeout:

It executes code after the set amount of time has passed. It accepts the function and delays time in milliseconds. It is an asynchronous function so it will not pause the execution of other functions in the function stack. It will be executed only after all functions in the program are executed.

Example 1:

const myFunc=()=>{
    console.log("This will be played after 6 seconds")
}
setTimeout(myFunc,6*1000)

Output:

This will be played after 6 seconds
setTimeout(function() {
  console.log('This message will be printed after 1 second');
}, 1000);

Example 2:

const myFunc=(param)=>{
    console.log(param+" This will be played after 2 seconds")
}
setTimeout(myFunc,2*1000,"FIRST")

Output:

FIRST This will be played after 2 seconds

 

Using async and await:

In this code, execution pauses until a promise is resolved. It is resolved when the resolver gets fired on the execution of setTimeout() which is executed after a delay of the time mentioned. It allows you to run asynchronous code as it was synchronous. It will pause the execution of other functions until await code is executed. Only within the async function you can use await.

Example 3:

function delay(time) {
    return new Promise(resolve => setTimeout(resolve, time));
}
 
async function printSent()
{ 
    console.log("No delay:Hello World")
    await delay(3000);
    console.log("Will be printed after 3 seconds");
    console.log("No delay:Will be printed");
}
 
printSent();

Output:

No delay:Hello World
Will be printed after 3 seconds
No delay:Will be printed

Another example:

async function delay(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

async function delayedLog() {
  console.log('This message will be printed after 1 second');
  await delay(1000);
  console.log('This message will be printed after another second');
}

delayedLog();

 

Using setInterval()

We can also use the setInterval() function to execute a function repeatedly with a specified interval in milliseconds. For example:

setInterval(function() {
  console.log('This message will be printed every 2 seconds');
}, 2000);

Using setImmediate()

We can use the setImmediate() function to execute a function as soon as possible, but after the current function has been completed.

setImmediate(function() {
  console.log('This message will be printed after the current function has completed');
});

Leave a Reply

Your email address will not be published. Required fields are marked *