Apart from the timeout
option, generally jQuery doesn't decide. You decide.
The routine is to always have a reference of what $.ajax()
returns you.
Meaning, instead of just calling $.ajax()
, do this instead, xhr = $.ajax()
.
$.ajax()
returns you a jqXHR object, which is just a jQuery wrapper of the Ajax functionality. See http://api.jquery.com/jQuery.ajax/
Now that you have xhr
, you can call xhr.abort()
from anywhere you want.
Really depends on how you design it, but you make the .abort() call. The following might be one possible use case.
One polling function, and another function that checks if user has been idle for too long.
In case the user is idle, abort the polling ajax, then perhaps prompt a message warning the user that the session is over.
Example use case:
var mainXHR; // this is just one reference.
// You can of course have an array of references instead
function mainPollingFunction () {
mainXHR = $.ajax({
url: 'keepAlive.php',
// more parameters here
timeout: 10000, // 10 seconds
success: function () {
// server waits 10 seconds before responding
mainPollingFunction(); // initiate another poll again
}
});
}
// Let's say this function checks if the user is idle
// and runs when a setTimeout() is reached
function otherFunction () {
if ( /* if user is idle */ ) {
if (mainXHR) mainXHR.abort(); // abort the ajax in case it's still requesting
}
}