Re: Open Source Cross-Browser setImmediate in JavaScript

On Wed, Jul 6, 2011 at 9:08 PM, Domenic Denicola <> wrote:

> > Thanks both of you for the feedback.  Could you give some examples
> (ideally with code) of when you would want to use setImmediate() and why
> existing mechanisms (like setTimeout()) are not ideal?
> > - James
> One example in my own projects is a pub-sub system. pub('eventName') is
> implemented, by design, to yield immediately to the calling code and
> execute
> any subscribing callbacks whenever there is a break in the event loop that
> allows for the (possibly computationally-intensive) callbacks to be
> executed. And since they are each fired with separate setImmediate calls,
> they yield independently.

This seems like a case where setTimeout(..., 0) should do exactly what you
want.  Have you found that it doesn't?

> Another common use case is to work around rendering timing issues. It seems
> that in some cases, at least according to comments that I've left for
> myself, adding a class to an element does not immediately change the
> computed characteristics of the element---especially when e.g. scrolling
> things into view is involved. I have previously used setTimeout(, 0) to
> work
> around this and yield until such a time as the rendering has completed and
> the event loop comes back around to process my code that depends on the
> now-updated computed characteristics. setImmediate is more efficient and
> much clearer as to why I am delaying, and I don't believe this is the
> intended use of requestAnimationFrame either.

This sounds more like a bug than a missing feature.  You shouldn't need to
do things like this in general.

> A final common case is to fire off an expensive operation, often
> interfacing
> with a browser plugin or some other piece of code that will hang the
> browser
> for a half-second. In this case, calling setImmediate allows the UI to
> update in response to the triggering event, instead of stalling until the
> plugin returns control to the browser UI thread and only then showing both
> the result of the plugin's work and the updated UI. This of course applies
> equally well to computationally-intensive JavaScript code.

Again, I think setTimeout(..., 0) should do the right thing here.

>  I can continue trawling my source code for uses of setTimeout(, 0), or
> nextTick, but in general they are all instances where I need to yield to
> calling code, or to the UI, which I believe was the intent of setImmediate.
I think there's some confusion here about what setImmediate() does.  It's
the exact same thing as setTimeout() except for the clamping behavior when
nesting, which should not come in to play in the cases you've mentioned.

- James

> -Domenic

Received on Tuesday, 12 July 2011 22:54:44 UTC