How do you do this without sleep in javascript

  • 2020-03-30 03:07:01
  • OfStack

Sleep is not available in javascript, and we'll use it for some time.

One idea is to run a loop so that the program runs out of CPU time to achieve delay. There is a drawback to this, the CPU execution speed of different machines is not the same, which is easy to cause the slow machine will SLEEP for a long time.

I've seen a clever solution from another forum that performs at the same speed on different machines. Here to share with you.
 
function sleep(n) 
{ 
var start=new Date().getTime(); 
while(true) if(new Date().getTime()-start>n) break; 

} 

Of course, this method still relies on idle CPU method.

Another method is to use the setTimeout() function.

SetTimeout (code,millisec)

Examples of use:

Var t = setTimeout (" alert (' 5 seconds! ') ", 5000).

The function of this code is to execute the code after millisec, in this example the alert function is executed after 5000 milliseconds. You can achieve the same effect as sleep.

Related articles: