Logo

dev-resources.site

for different kinds of informations.

JavaScript has no sleep function, but we can easily solve it this way!

Published at
6/21/2023
Categories
javascript
promise
sleep
tips
Author
danielzotti
Categories
4 categories in total
javascript
open
promise
open
sleep
open
tips
open
Author
11 person written this
danielzotti
open
JavaScript has no sleep function, but we can easily solve it this way!

In order to make your browser sleep, just write this line of code:

await new Promise(_ => setTimeout(_, 2000));
Enter fullscreen mode Exit fullscreen mode

This will make the browser sleep for 2 seconds (2000ms).

Please note that it works in modern browsers only (> 2017)! See browser compatibility for await on caniuse.com.

Let's create a reusable sleep function

const sleep = (ms = 2000) => new Promise(_ => setTimeout(_, ms));
Enter fullscreen mode Exit fullscreen mode

Or with a more old days' notation:

function sleep(ms = 2000) { 
  return new Promise(function(_) {
    return setTimeout(_, ms)
  });
}
Enter fullscreen mode Exit fullscreen mode

If you want to explore other features of Promise you can browse the MDN Doc.

How to use it

console.log(`Let's wait for 5s`);

await sleep(5000); // 5000ms = 5seconds

console.log(`5s have passed`);
Enter fullscreen mode Exit fullscreen mode

Result in console:

> Let's wait for 5s
[waiting for 5 seconds]
> 5s have passed 
Enter fullscreen mode Exit fullscreen mode

Top-level await issue

Using top-level await might not work in some old browser/node versions. To solve this problem we can wrap our code
with an immediately-invoked async function.

(async function() {

  console.log(`Let's wait for 5s`);

  await sleep(5000);

  console.log(`5s have passed`);

}());  
Enter fullscreen mode Exit fullscreen mode

Sleep function in old browsers

Just a note about Sleep function in old browser: it has usually been written this way, but it's definitely not
"performance friendly".

function sleep(mss) {
  const date = Date.now();
  let currentDate = null;
  do {
    currentDate = Date.now();
  } while(
    currentDate - date < milliseconds);
}
Enter fullscreen mode Exit fullscreen mode

Demo

I created a stackblitz project with a simple example.

sleep Article's
28 articles in total
Favicon
Effective Gentle Sleep Training Methods: Helping Your Baby Sleep Peacefully
Favicon
Effective Gentle Sleep Training Methods: Helping Your Baby Sleep Peacefully
Favicon
The Side Effects of Using Smartphones Before Sleep and How to Overcome This Habit πŸš€
Favicon
Discover the Best Silk Pillowcase: Ultimate Guide to Luxurious Sleep
Favicon
The Science of Sleep: How AI-Powered Sleep Trackers and Smart Mattresses Can Transform Your Sleep Quality
Favicon
Understanding Lunesta 3 mg: Best Cure for Insomnia
Favicon
The Fascinating World of Dreams Unraveling the Mysteries of Our Sleeping Mind
Favicon
Sleeping Underwater How Do Dolphins Sleep Without Drowning
Favicon
Implement a true "sleep" function in Node.js
Favicon
Finding the Perfect Sleep
Favicon
Sleep Disorder Predictor
Favicon
How One Can Repair Widespread Daytime Sleepiness Issues
Favicon
JavaScript has no sleep function, but we can easily solve it this way!
Favicon
Sleep Apnea Is A Serious Issue, Know About It In Detail
Favicon
Sleep and Be Productive
Favicon
Programming Tip #5: Sleep
Favicon
Working full-time and hacking a side project: It’s not possible.
Favicon
What is the JavaScript version of sleep()?
Favicon
Improve Your Sleep (as a Developer) πŸ’€
Favicon
I did hustleTwitter for 30 days. Here's what I learned
Favicon
The SHAME ON ME fix
Favicon
Want to be a better developer? Take care of your sleep!
Favicon
How I managed to control my insomnia
Favicon
About A Good Night's Rest
Favicon
Let's talk about sleep.
Favicon
The Lying Desk and the Patate Technique
Favicon
Less Blue Light, Better Sleep
Favicon
Baltimore at 4:45am

Featured ones: