small medium large xlarge

Back to: All Forums  PragPub
Trevor_burnham__goofy_headshot__pragsmall
09 May 2011, 16:27
Trevor Burnham (54 posts)

In the article (A CoffeeScript Intervention, http://pragprog.com/magazines/2011-05/a-coffeescript-intervention), I wrote that

for i in [1..3]
  do (i) ->
    setTimeout (-> console.log i), 0

will give you the output

1
2
3

As a reader pointed out to me, the order in which the timeout events will resolve isn’t actually guaranteed by the JavaScript spec. So while the output above is most likely, you could easily find yourself getting

3
2
1

in some browsers. It’s tangential to what I was talking about, but worth being aware of.

To ensure that the output order is consistent across all environments, simply use @i@ instead of @0@ as the timeout interval.

You must be logged in to comment