This page looks best with JavaScript enabled

Sleep Function in Javascript

 ยท   ยท  โ˜• 1 min read

Sleep holds off your function execution for specified time. This is super useful whenever you want to hold off something for โ€˜xโ€™ time.

Here are two ways in which you can get your program to sleep for a while.

setTimeOut

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
function sleep() {
  console.log("trying to sleep..");
  setTimeout(() => {
    console.log(".. woke up after 3s");
  }, 3000);
}

/* output
trying to sleep..
.. woke up after 3s
*/

sleep();

Promise / async-await

You could async the whole function to make it cleaner but there is no visible change to how your program executes :)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
const sleep = async () => {
  setTimeout(() => {
    console.log(".. woke up refreshed ");
  }, 3000);
};

const goToSleep = async () => {
  await sleep();
  console.log("I am still here..");
};

/* output
I am still here..
.. woke up refreshed 
*/

Note that -

  • The program itself does not go to sleep, only the function with timeout statement does. See details on Javascript event loop to know how Javascript processes your program instructions.

  • Do not use this sleep pattern for checking things and doing stuff. Use promises instead.

Stay in touch!

Tech in your inbox - news, tips, and summary of our posts. 2 emails per month.

Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things