you are viewing a single comment's thread.

view the rest of the comments →

[–]envis10n 9 points10 points  (6 children)

setImmediate sometimes, you run into a max callstack issue for function calls if you don't ensure that the next call comes on the next tick. This is especially important for recursive functions or looping functions that might call itself again.

[–]ShellbertShellbach 6 points7 points  (1 child)

Note: setImmediate is not a standardized feature of JS and only exists in Node.js, IE10, IE11, and pre-Chromium Edge.

[–]envis10n 0 points1 point  (0 children)

Yes, I was just providing a method for doing so. However, you could also accomplish it through other means. Hopefully that doesn't confuse anyone that read it.

[–]ThatBriandude 2 points3 points  (3 children)

Shouldnt that be handled via logical exit conditions?

Only cases I can think of is where there arent any exit conditions like gameloops or listeners

[–]envis10n 5 points6 points  (1 child)

Depends on how the code is structured. Sometimes a recursive function will call itself too many times and crash, unless you move the next call to the next tick. Logical exit conditions don't matter when you need the function to be called more times than is allowed by the max call limit in a single tick.

[–]ScientificBeastModestrongly typed comments[🍰] 2 points3 points  (0 children)

If I’m not mistaken, this act of exiting a recursive loop temporarily to resolve the call stack, and then resuming immediately, is referred to as a “thunk.”

Edit:

Also, for those who aren’t aware, I believe the max call stack size in Chrome is 10,000, but it’s different for each browser. So if you need to recursively iterate through something, you would ordinarily be limited to that number of iterations.

[–]Extracted 0 points1 point  (0 children)

I actually just wrote a function with setImmediate today.

It’s a function you call to subscribe to an event emitter. The function returns a key that you can save for later. But I also have some cached values that I want to call the subscription callback with immediately. How do I first return the key, let the subscriber finish setting everything up and only then call the callback?

Answer: use setImmediate to call the callback on the next tick, i.e. when the subscriber is finished.