How to put your JavaScript function to sleep

Learn how to use JavaScript to sleep a function for a certain period of time

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

In a programming language like C or PHP, you would callsleep(2)Pause the program for 2 seconds. Java hasThread.sleep(2000), Python hastime.sleep(2),wenttime.Sleep(2 * time.Second).

JavaScript does not have a native sleep function, but due to the introduction of Promise (and async/await in ES2018), we can implement this function with very good readability to put your function into sleep:

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

Or, in Node.js, it's simpler:

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

see morecommitted to

You can now combine it withthencall back:

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

Or use it in an asynchronous function:

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

doSomething()

Remember, because of how JavaScript works, please read more.Event loop), this will not suspend the execution of the entire program like other languages, but will only put your function to sleep.

You can apply the same concept to loops:

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

doSomething()

Download mine for freeJavaScript beginner's manual


More js tutorials: