Reputation: 1809
Is it possible for an ajax request to return a timeout, because the JavaScript thread is unavailable?
Say I send a request, after which the backend returns a success code ~500 ms later. Immediately after sending the request, I perform a really expensive function (using practically all CPU for 10 seconds), will my request end up as en error due to the timeout, or as a success because it was the function returned after 500ms?
$.ajax({
url: "my/url",
error: function(){
//do something
},
success: function(){
//do something
},
timeout: 5000
});
expensiveFunction(); //takes 10 seconds
Upvotes: 0
Views: 193
Reputation: 2842
Why not try it? It's the best way to find these things out.
Note - running the below snippet will probably lock up your browser for about 5 seconds.
document.getElementById('start').addEventListener('click',startAjaxRequest);
function startAjaxRequest() {
var errorTimer;
function asyncFunction(callback) {
errorTimer = setTimeout(fail, 2000);
document.getElementById('FakeServerResponse').addEventListener('click',callback);
}
function fail() {
console.log("Error!");
}
function cpuHog() {
var startTime = new Date().getTime();
var i = 0;
while(startTime > new Date().getTime() - (1000 * 5)) {
i++;
}
console.log("Cpu Hogging process is done");
return i;
}
asyncFunction(function() {
clearTimeout(errorTimer);
console.log("Async process is complete");
});
setTimeout(cpuHog,0);
}
<button id="start">Start!</button>
<button id="FakeServerResponse">Click to fake the Server Responding</button>
Try clicking start then immediately clicking the "Click to fake the Server Responding" button. You'll see the console says the process is complete.
Then try clicking start and not faking the server response. You'll see the error callback is hit.
This is because when new events (literal events triggering, or timeouts firing) occur in javascript, they are added to a "message queue" which is evaluated one by one when javascript has time. When the server responds to your request, an event is fired inside jquery (readystatechange) which is added to that message queue. Similarly, your timeout (of 2000ms in the example I have created) is just placed in a setTimeout inside jquery. When the timeout is up, an event is added to the message queue to evaluate that timeout. So long as this event is added after the server responded, the server response will be evaluated first. If the timeout gets hit before the server responded, then the error will occur first.
Upvotes: 2