Pause an async function for 3 seconds in Node.js?

Answered
itsbambi asked this question 1 year, 5 months ago
itsbambi on Dec 7, 2021

I have an async function that I want to pause for 3 seconds.

const uploadImage = async function() {
  // do some stuff

  // pause for 3 seconds

  // do some more stuff
}

Is it possible to do that? And if so, how?

2 suggested answers
looper003 on Dec 7, 2021

Insert this line of code in your function wherever you want the pause to occur:

await new Promise(r => setTimeout(r, 3000))

This code creates a Promise and resolves it after 3000 milliseconds (or 3 seconds) using a setTimeout() function.

You could use it in your function like this:

const uploadImage = async function() {
  // do some stuff

  await new Promise(r => setTimeout(r, 3000))

  // do some more stuff
}
0 replies
coderguy on Dec 7, 2021

Here's an implementation of a sleep() function you could use in your async functions.

This is the sleep() function:

const sleep = function(seconds) {
  const milliseconds = seconds * 1000 // convert seconds to milliseconds for the setTimeout() function

  return new Promise(r => setTimeout(r, milliseconds))
}

This function takes a seconds parameter and resolves/returns a promise after that amount of time has elapsed. When called, it will pause only the current async function it's inside of.

Here's how you'd use it:

const uploadImage = async function() {
  console.log("Pause has begun.")

  await sleep(3)

  console.log("Pause has finished.")
}
0 replies
Answered