DEV Community

Discussion on: Sleep function in javaScript

Collapse
 
qm3ster profile image
Mihail Malo

I usually write it as

const sleep = ms => new Promise(res => setTimeout(res, ms))
Enter fullscreen mode Exit fullscreen mode

since there's no reason to introduce an additional closure.
You can also do that with value (that promise will resolve to) since setTimeout supports passing arguments.

const sleep = (ms, v) => new Promise(res => setTimeout(res, ms, v))
sleep(500, "hello").then(console.log)
Enter fullscreen mode Exit fullscreen mode
Collapse
 
ats1999 profile image
Rahul kumar

Although great example
const sleep = ms => new Promise(res => setTimeout(res, ms))

Collapse
 
ats1999 profile image
Rahul kumar

.then(console.log)
I usually avoid to chaining in this case. Await would be great fit here.