DEV Community

Discussion on: Sleep function in javaScript

Collapse
 
ironcladdev profile image
Conner Ow

Why would you go through all that work of creating a javascript promise when you can just use the setTimeout function and the clearInterval function?

Collapse
 
lionelrowe profile image
lionel-rowe • Edited

To avoid "callback hell". Promises with async/await allow you to write asynchronous code linearly, rather than nesting callbacks, which quickly becomes messy.

If you might need to clear the timeout before it executes, the callback version is probably better though (you could build a clearable promise version, but it would be less easy to work with). Depends on your use case.

Collapse
 
ats1999 profile image
Rahul kumar

agree

Collapse
 
ats1999 profile image
Rahul kumar

Supposed in case, where you want to use sleep many times. If code goes long, say 1000 lines of code. In this case, it becomes hard to manage the code.
Here we can just use,

await sleep(ms);
// do after sleep();
Enter fullscreen mode Exit fullscreen mode
Collapse
 
ats1999 profile image
Rahul kumar

code and sleep 🥱