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

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?

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)