Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the equivalent of Java's Thread.sleep() in JavaScript? [duplicate]

What's the equivalent of Java's Thread.sleep() in JavaScript?

like image 447
Niger Avatar asked Oct 01 '22 15:10

Niger


1 Answers

The simple answer is that there is no such function.

The closest thing you have is:

var millisecondsToWait = 500;
setTimeout(function() {
    // Whatever you want to do after the wait
}, millisecondsToWait);

Note that you especially don't want to busy-wait (e.g. in a spin loop), since your browser is almost certainly executing your JavaScript in a single-threaded environment.

Here are a couple of other SO questions that deal with threads in JavaScript:

  • JavaScript and Threads
  • Why doesn't JavaScript support multithreading?

And this question may also be helpful:

  • setTimeout - how to avoid using string for callback?
like image 238
Daniel Pryden Avatar answered Oct 27 '22 06:10

Daniel Pryden