const sleep = (ms) => (new Promise(resolve => setTimeout(resolve, ms)));
It's the JS version of the sleep command that I so miss from a lot of languages like Python and BASIC. The new async/await syntax allows you to call this function with a simple await sleep(2000); wherever you feel like it. Incredibly useful for games, animations and every time you need a timeout.
Yeah this is more in line with what sleep usually means in other languages I mentioned, i.e. preventing the thread from running any other operation for a given duration.
Because when you use await on it it looks like synchronous code. How are you going to use setTimeout in purely imperative code without screwing up your flow?
Yeah, so without using promise the code below setTimeout will run right after registering the setTimeout callback in the event loop. But if we use promise, it will stop the execution of the funtion right?
114
u/EllisLloyd Mar 19 '19 edited Mar 19 '19
This:
It's the JS version of the sleep command that I so miss from a lot of languages like Python and BASIC. The new async/await syntax allows you to call this function with a simple
await sleep(2000);wherever you feel like it. Incredibly useful for games, animations and every time you need a timeout.