JS sleep (setTimeout) using promises in one line of code.

Update: Prefer const over let

As mentioned before, I like JavaScript promises.

One nice trick with promises is creating a simple sleep function using the standard setTimeout.

Here’s the line of code:

const sleep = (time) => new Promise((resolve) => setTimeout(resolve, time));

Then use it as:

sleep(500).then(() => {
    // Do something after the sleep!

A nice simple sleep function in JavaScript.

Leave a Reply

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