Sleeping in JavaScript

Nino Filiu
2 min readDec 20, 2018

“I’m used to the sleep() function which exists in C, Python, Bash, and many other. How can I sleep in JavaScript?”

You can’t. There is no sleep function in JavaScript.

But you can create something very similar

const sleep = ms => new Promise(resolve => {
setTimeout(
() => {resolve()},
ms
);
});

This creates a Promise that will resolve in ms milliseconds, so you can use it with Promise.then(callback)

console.log(Date());
sleep(1000).then(() => console.log(Date()));

But it does not looks like the sleep from other programming languages. A way to make it more C-esque is the following:

(async () => {
console.log(Date());
await sleep(1000);
console.log(Date());
})();

In this implementation, await is used to keep the code before the promise and after the promise in the same block. However, await can only be used inside of asynchronous functions. More about await/async

Additionally, this sleep does not keep the CPU busy while waiting, since it uses setTimeout to wake up.

Ok, so now you can sleep in JavaScript. But… should you?

Well, nobody is stopping you. We live in a free country and it’s up to you to do whatever you want with your code. Make an infinite loop. Crash your computer. Hack the NSA. Program in Java. Just kidding, don’t do the last one.

On a more serious note, there is no sleep function in JS because the language was built for asynchronous operations: upon event X, do function Y, contrary to synchronous languages: do task A, then do task B, then do task C.

What most people have in mind when they try to sleep in JS is the following:

1. do task A
2. do task sleep for 1 second
3. do task B

But it’s not really compatible with the philosophy of JS and asynchronous programming. Instead, people should have this in mind:

1. do task A
2. in one second, an event will happen that will trigger task B

And that’s exactly what setTimeout does:

taskA();
setTimeout(() => taskB(), 1000);

In a nutshell, the sleep function described in the beginning of the article can be used to have a cleaner, simpler code. But under the hood, there will always be an event, and a callback.

--

--

Nino Filiu

I guess you guys aren’t ready for what I code yet, but your kids are gonna love it. ninofiliu.com