r/javascript • • May 28 '19

What are some JavaScript things beginners don't know?

333 Upvotes

383 comments sorted by

View all comments

Show parent comments

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).

8

u/ShellbertShellbach May 28 '19

Less standard? How about not standard at all?

1

u/ScientificBeastMode strongly typed comments May 28 '19

Yeah, just an IE/Edge thing for now (I assume Edge won’t implement it once they roll out Chromium-based Edge). I’m honestly surprised that other browsers haven’t implemented it since it has always been a popular proposal on the front-end dev side of things, but I’m sure there are some very good reasons I don’t know about.

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.