Sleep in JavaScript delay between actions?

JavascriptWeb DevelopmentObject Oriented Programming

To set sleep i.e. delay, use the concept of setTimeout(). It takes values in milliseconds i.e.

1000 milliseconds = 1 second
2000 milliseconds = 2 seconds, etc.

For our example, we will add two values with a delay of 5 seconds i.e. 5000 milliseconds. Following is the code −

Example

var firstValue=10;
var secondValue=20;
var result=firstValue+secondValue;
setTimeout(function() {
}, (5 * 1000));
console.log("The result="+result);

The above setTimeout() will sleep for 5 seconds. To run the above program, you need to use the following command −

node fileName.js.

Here, my file name is demo95.js.

Output

This will produce the following output −

PS C:\Users\Amit\JavaScript-code> node demo95.js
The result=30
raja
Published on 07-Sep-2020 08:33:35
Advertisements