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
	sleep(60)
	
	console.log("Code after delay");
}
logoblog

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

Previous
« Prev Post

No comments:

Post a Comment

How to send email from current Outlook instance using Java + VBScript

If we are using .Net, we can easily access outlook and send emails using its own libraries. But what if we are using Java? Here we can seek ...