</div>
</div>
<div class="grid--cell mb0 mt8">Closed <span title="2012-08-23 06:31:08Z" class="relativetime">7 years ago</span>.</div>
</div>
</aside>
Possible Duplicate:
Why does setTimeout(fn, 0) sometimes help?
Reading jQuery 1.8 source,
WHY does it do setTimeout with 0 ms delay ? (instead of just executing the callback ?)
https://github.com/jquery/jquery/blob/1.8.0/src/ajax/xhr.js#L196
if ( !s.async ) {
callback();
} else if ( xhr.readyState === 4 ) {
// (IE6 & IE7) if it's in cache and has been
// retrieved directly we need to fire the callback
//-------->// WHY do setTimeout with 0 ms delay ?
setTimeout( callback, 0 );
} else {
handle = ++xhrId;
</div>
The reason is that setTimeout adds the function to the browser event queue so it will only be invoked after the preceding events in the queue have been handled, allowing the rest of the function that sets the timeout to finish execution.
This is a workaround for a peculiarity of IE6 and IE7 which can retrieve an AJAX result from cache without firing the XMLHTTPRequest
callback, immediately setting its readyState
property to 4
, instead.
However the API contract for $.ajax
requires that it return immediately for an asynchronous request (i.e. without calling the programmer-supplied callbacks).
Hence $.ajax
call tests for those cached results, and then fakes the required asynchronous callback using setTimeout
.
The $.ajax
call completes, and as soon as the browser re-enters its event processing loop it'll find the (immediately expired) timer event and call its callbacks.