DEV Community

loading...
Cover image for Wait!

Wait!

Thomas Rigby
When I'm not building things for the internet, I take photos of stuff. Code Janitor. 1x Engineer.
Originally published at thomasxbanks.com on ・1 min read

Why the rush…?!

Whether you're faking an API response, introducing deliberate cognitive drain, or simply want to slow things down this utility function has got you, baby! 😎

const delay = ms => new Promise(rv => setTimeout(rv, ms))
Enter fullscreen mode Exit fullscreen mode

Cool! How do I use it?

delay(500).then(() => console.log(`hello world`))
Enter fullscreen mode Exit fullscreen mode

Nice! Does it work with async/await?

Heck, yes, it does!

const functionName = async () => {

  doFirstThing()

  await delay(500)

  doNextThing()
}
Enter fullscreen mode Exit fullscreen mode

See the Pen Delay by thomas×banks (ツ) (@thomasxbanks) on CodePen.

Discussion (0)