Emulate Thread.sleep() in JavaScript

When you’re writing code in JavaScript and you need your function to wait some time, you usually use setTimeout(callback, millis). The problem with this function is that only the callback will be delayed, while the code next to it will run normally. How do you actually stop the execution of the application for a certain amount of time, like Java’s Thread.sleep() does?

You can do that thanks to ES8.

The trick here is to take advantage of a few function keywords made available by ES8 (ES2017). These keywords are async and await.

Be sure your browser supports this standard: https://caniuse.com/#feat=async-functions

The first thing you do is declare a sleep() function, which takes an amount of time in milliseconds as a parameter:

Then, in your main function, you just have to call await sleep(<amount>); to pause the execution! Take note, however, that for this method to work you have to declare you main function with async. Here’s an example:


And you’re done! That’s all you need to have a Thread.sleep() equivalent in JavaScript.

One Comment

Add a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.