JS: Thread.sleep function | JavaScript
Thread.sleep function
How to sleep the thread as Thread.Sleep do in C#, Java etc. This article has the code example of sleeping the thread, through function that takes input miliseconds are arguments.
There is no built-in function that could be the equivalent of Thread.Sleep in Java, C# and other programming languages. We can achieve this with the following code snipet.
function sleep(ms){
if(ms <= 0)
return;
var c = Date.now();
var to = c + ms;// TimeOut;
while(true){
if(Date.now() > to){
return; //terminates the while loop and returned
}
}
}
- The function sleep passes sleep-duration as miliseconds ms.
- First we have taken the current time in c.
- Add current time c with sleep-duration ms to get timeout.
- Start
while
loop for inifinte time - The
if
condition to check on each iteration until the current time is less than timout to.
sleep
function usage:
console.log(new Date());
sleep(3000);
console.log(new Date());
Sun Mar 27 2022 15:13:01
Sun Mar 27 2022 15:13:04
First print the current date time on the console using new Date()
, then sleep the thread for 3 seconds (3000 miliseconds), then print the current date time again. We spot the difference of 3 seconds between both printings.