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.

15

u/higherpublic Mar 19 '19

const sleep = (data, ms) => (new Promise(resolve => setTimeout(()=> resolve(data), ms)));

For sleeping between then()’s and passing data between after the sleep

25

u/FormerGameDev Mar 19 '19

Make Ms the first param

22

u/dougalg Mar 19 '19

If we're going there, why not:

const sleep = (ms) => (data) => new Promise(resolve => setTimeout(()=> resolve(data), ms));

Which gives you a nice thing like:

makeApiCall().then(sleep(1000)).then(processData)

19

u/tjoskar Mar 19 '19

If we're going there, why not:

const sleep = ms => data => new Promise(resolve => setTimeout(resolve, ms, data))

😉

3

u/higherpublic Mar 19 '19 edited Mar 19 '19

No way. Such elegance!! How is data from the api call not getting passed in as the ms though?

Edit: never mind I see it now

1

u/TheKingdutch Mar 19 '19

TIL: about extra parameters for setTimeout. Thanks!

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.

1

u/[deleted] Mar 20 '19

[removed] — view removed comment

2

u/BenZed Mar 25 '19

It definitely does not invoke a system call.

1

u/reyhanahmed Mar 25 '19

Why wrap it in a promise? setTimeout should work.

3

u/EllisLloyd Mar 25 '19

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?

1

u/reyhanahmed Mar 25 '19

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?

2

u/EllisLloyd Mar 25 '19

Yeah exactly

1

u/reyhanahmed Mar 25 '19

Cool, thanks!

1

u/[deleted] Mar 19 '19

Neat! I like it.