JavaScript (in the browser at least) works with an event queue and the main thread polling that queue. When you call Scheduler.scheduleDeferred
, setTimeout
is called in JavaScript with a delay of 1 millisecond. This will queue a "timer fired" event in the browser after the delay has expired, with the SchedulerCommand
you passed as argument (actually, there's another queue involved within Scheduler
, but that doesn't change the overall flow of actions).
So, what your code is saying here is: delay "In task1" by 1 millisecond, then print "In task2", then after 1 millisecond (and after possibly processing other events present in the queue), print "In task1".
See http://www.whatwg.org/specs/web-apps/current-work/multipage/timers.html#dom-windowtimers-settimeout for the gory details of how setTimeout
works in browsers.