Javascript: The sleep version of it

P. George
1 min readAug 21, 2020

--

Javascript has been this synchronous language since forever, and it took me a while to shift my mind to understand the recent async/await concepts.

Recently I needed to make a simple sleep within a function, but there’s no builtin for that. How the hell can I make a simple sleep without blocking the main thread??

Here’s what I ended up finding on StackOverflow, using a simple promise and a timeout to resolve it:

Photo by Danial Mesbahi on Unsplash
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}

Usage:

await sleep(5000);

--

--

P. George

I’m a senior developer, love to face new challenges that make me learn and struggle. A primate with sophisticated tools. Also stoic AF.