September 5, 2022

Thread.Sleep equivalent in Java Script (Node JS)

  September 5, 2022
As we know, in Node JS the code is executed asynchronously. Asynchronous functions are functions that do not block the execution of the program whereas synchronous functions block the execution of the program until it has finished processing. In synchronous execution function like in C# and Java we can use Thread.Sleep and similar methods to explicitly wait for sometime in between execution. But what happens , if we are using a Node JS and we need to apply wait between different lines of code? 
 Below given is a workaround for such situations. Here we takes the idea of while loop + Date time method. We will create a method which will loop until the required time with time interval in seconds. 

 One such method is given below.
function sleep(seconds) {

    var e = new Date().getTime() + (seconds * 1000);
    while (new Date().getTime() <= e) {}

This method can be called inside our synchronous method which will work similar to Thread.Sleep and our code will wait the mention seconds till executing the next line

Sample usage 

function SampleDelayMaker(){

	console.log("Code before delay");
	//Waits 60 seconds in this line
	console.log("Code after delay");

Thanks for reading Thread.Sleep equivalent in Java Script (Node JS)

« Prev Post

No comments:

Post a Comment

Bookmark this website for more workarounds and issue fixes.

Verify Zip file contents without extracting using C# + Selenium

While doing automation testing, we may get a scenario where we need to download a zip file and to validate the contents inside it. One way t...