In my web app I'm using a dialog with a spinner to indicate that the app is waiting for a server response. It's supposed that by clicking on Cancel button a user may stop waiting for the response.
I implemented this like the following:
function waitForResponse () {
// pull jsons until it's ok
$.ajax({
url: ...,
dataType: 'json'
}).done(function (rsp, status) {
// OK. Close the wait dialog.
$('div#waitdialog').dialog('close');
}).fail(function (rspobj, status, msg) {
// Not yet. Pull it again.
setTimeout(waitForResponse, 3000);
});
}
$('<div id="waitdialog">')
.appendTo('body')
.append(spinner())
.dialog({
buttons: {
Cancel: function () {
$(this).dialog("close");
}
},
close: function (event, ui) {
$(this).remove();
}
});
waitForResponse();
The problem is I have no idea how to stop pulling jsons on Cancel click. I'd use a global variable, however I don't think this is good approach.
UPD. The question is not about how to stop an ajax request. It's about how to notify the pulling procedure in proper way avoiding global variables.