Skip to content

How to make your JavaScript functions sleep

Learn how to make your function sleep for a certain amount of time in JavaScript

Sometimes you want your function to pause execution for a fixed amount of seconds or milliseconds.

In a programming language like C or PHP, you’d call sleep(2) to make the program halt for 2 seconds. Java has Thread.sleep(2000), Python has time.sleep(2), Go has time.Sleep(2 * time.Second).

JavaScript does not have a native sleep function, but thanks to the introduction of promises (and async/await in ES2018) we can implement such feature in a very nice and readable way, to make your functions sleep:

const sleep = (milliseconds) => {
  return new Promise(resolve => setTimeout(resolve, milliseconds))
}

or, in Node.js, simpler:

const { promisify } = require('util')
const sleep = promisify(setTimeout)

See more on promisify

You can now use this with the then callback:

sleep(500).then(() => {
  //do stuff
})

Or use it in an async function:

const doSomething = async () => {
  await sleep(2000)
  //do stuff
}

doSomething()

Remember that due to how JavaScript works (read more about the event loop), this does not pause the entire program execution like it might happen in other languages, but instead only your function sleeps.

You can apply the same concept to a loop:

const list = [1, 2, 3, 4]
const doSomething = async () => {
  for (const item of list) {
    await sleep(2000)
    console.log('🦄')    
  }
}

doSomething()

→ Get my JavaScript Beginner's Handbook

download all my books for free

  • javascript handbook
  • typescript handbook
  • css handbook
  • node.js handbook
  • astro handbook
  • html handbook
  • next.js pages router handbook
  • alpine.js handbook
  • htmx handbook
  • react handbook
  • sql handbook
  • git cheat sheet
  • laravel handbook
  • express handbook
  • swift handbook
  • go handbook
  • php handbook
  • python handbook
  • cli handbook
  • c handbook

subscribe to my newsletter to get them

Terms: by subscribing to the newsletter you agree the following terms and conditions and privacy policy. The aim of the newsletter is to keep you up to date about new tutorials, new book releases or courses organized by Flavio. If you wish to unsubscribe from the newsletter, you can click the unsubscribe link that's present at the bottom of each email, anytime. I will not communicate/spread/publish or otherwise give away your address. Your email address is the only personal information collected, and it's only collected for the primary purpose of keeping you informed through the newsletter. It's stored in a secure server based in the EU. You can contact Flavio by emailing [email protected]. These terms and conditions are governed by the laws in force in Italy and you unconditionally submit to the jurisdiction of the courts of Italy.

Related posts about js: