0

I want to implement a sleep function that functions like the following like this:

console.log(123)
slepp(2000)
console.log(456)

run it:

123
waiting two seconds...
456

I want to get a solution about sleep function implements

vikoala
  • 19
  • 1
  • Please visit [help], take [tour] to see what and [ask]. Do some research, search for related topics on SO; if you get stuck, post a [mcve] of your attempt, noting input and expected output, preferably in a [Stacksnippet](https://blog.stackoverflow.com/2014/09/introducing-runnable-javascript-css-and-html-code-snippets/) – mplungjan Mar 05 '23 at 09:55

2 Answers2

2

Did this myself just the other day on a project.

function sleep(delay) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve();
    }, delay);
  });
}

You can use by: await sleep(2000) for a 2 second delay.

John Detlefs
  • 952
  • 8
  • 16
  • if the add condition is not used await syntax, Is there another solution? This is an interview question I came across. – vikoala Mar 05 '23 at 12:55
2

Here's the function that I add to almost every project I have:

/**
 * Async function to sleep for `ms` amound of milliseconds.
 * @param ms - time to sleep in milliseconds
 * @returns `Promise<void>` after the sleep time has passed.
 */
export async function sleep(ms: number): Promise<void> {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve();
    }, ms);
  });
}

Edit: Looks like @John Detlefs beat me to it by 2 minutes, didn't notice it while the question was already open :)

Maher
  • 151
  • 13
  • Thank you for answer my question.But if the add condition is not used await syntax, Is there another solution? This is an interview question I came across. – vikoala Mar 05 '23 at 12:57
  • 1
    @vikoala as far as I am aware, it's not possible without async/await. Even if you use other libraries like lodash or RxJS to simulate sleeping with callback functions, they will eventually use Promises. – Maher Mar 06 '23 at 13:05