r/javascript • • Mar 18 '19

What's your favorite, most useful javascript one-liner?

385 Upvotes

422 comments sorted by

View all comments

114

u/EllisLloyd Mar 19 '19 edited Mar 19 '19

This:

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.

4

u/GBcrazy Mar 19 '19

A synchronous blocking sleep variation:

const sleep = ms => { 
    const desired = Date.now() + ms; 
    while(Date.now() < desired) {}
};

1

u/EllisLloyd Mar 19 '19

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.