HTML and CSS Reference
In-Depth Information
started and so we expect a new request to have fired immediately. The test fails and
Listing 13.37 shows how to pass it.
Listing 13.37 Using the interval as minimum interval between started requests
function start() {
/* ... */
var requestStart = new Date().getTime();
ajax.request(this.url, {
complete: function () {
var elapsed = new Date().getTime() - requestStart;
var remaining = interval - elapsed;
setTimeout(function () {
poller.start();
}, Math.max(0, remaining));
/* ... */
},
/* ... */
});
}
Running the tests, somewhat surprisingly, reveals that the test still fails. The clue
is the setTimeout call. Note that even if the required interval is 0, we make the
next request through setTimeout , which never executes synchronously.
One benefit of this approach is that we avoid deep call stacks. Using an asyn-
chronous call to schedule the next request means that the current request call
exits immediately, and we avoid making new requests recursively. However, this
cleverness is also what is causing us trouble. The test assumes that the new request
is scheduled immediately, which it isn't. We need to “touch” the clock inside the
test in order to have it fire queued timers that are ready to run. Listing 13.38 shows
the updated test.
Listing 13.38 Touching the clock to fire ready timers
"test should re-request immediately after long request":
function () {
this.poller.interval = 500;
this.poller.start();
var ahead = new Date().getTime() + 600;
stubDateConstructor(new Date(ahead));
 
Search WWH ::




Custom Search