Question

I have a doubt on how the Schedule defrred in GWT works.

I have the following function in my program:

function()
{
 doTask1();
 doTask2();
}

doTask1() {
 Scheduler.get.scheduleDeferred(new Scheduler.ScheduledCommand) {
  System.out.println("In task1");
 }
}

doTask2() {
 System.out.println("In task2");
}

What I expected is that the following will be the output:

In task1
In task2

But the output I am getting is:

In task2
In task1

Why is it so? My understanding was ScheduleDeferred only takes care of user input like mouse click etc. Does it also affect function behaviour in this way?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top