r/javascript • • May 28 '19

What are some JavaScript things beginners don't know?

333 Upvotes

383 comments sorted by

View all comments

105

u/ItalyPaleAle May 28 '19

The async programming model and especially how the event loop works.

The latter might be transparent to you 99.9% of the times, but then you’ll run into issues where your code behaves unexpectedly and you just need to execute it in the next tick (iteration of the event loop) instead.

12

u/ThatBriandude May 28 '19 edited May 28 '19

and you just need to execute it in the next tick (iteration of the event loop) instead.

I consider myself pretty well versed in javascript however I can not imagine what you mean with this. How would "execute it in the next tick" look in code?

3

u/archivedsofa May 28 '19

setTimeout(doSomething, 0);

4

u/ScientificBeastMode strongly typed comments May 28 '19 edited May 28 '19

setImmediate is less standard, but supposedly faster than setTimeout set to zero. It’s basically a native implementation of setTimeout( ... , 0).

2

u/itsnotlupus beep boop May 28 '19

My favorite way to run code asynchronously as tightly as possible (absent node's nextTick stuff) is to use Promise.resolve().then(...).

That will schedule a microtask, which may end up running after other scheduled microtask, but still long before anything else.
It's so fast it can often be "too fast", particularly if you're hoping the browser will redraw anything before calling your code again, the way a setTimeout(... ,0) would.

There are other approaches, like mildly abusing the postMessage API, but nothing as straightforward as an immediate promise.