I have an AJAX request that looks like this:
var statistics = "link-to-a-JSONP";
function team_stats(json) {
alert(json);
}
(function stats() {
$.ajax({
type: 'GET',
url: statistics + '?callback=jsonp',
crossDomain: true,
dataType: 'jsonp',
jsonpCallback: 'team_stats',
jsonp: 'callback',
data: {},
success: function(data) {
var test += '<div>' + data + '</div>';
$(".content").append(test);
/* a close button that closes the tab and kills the request */
$("#closeStats").on("click", function() {
stats.abort();
});
},
complete: function() {
setTimeout(stats, 15000);
}
});
})();
This works great and the request repeats itself every 15 seconds. Now, I want to kill the request when I click a certain button (as shown). The compiler says that the fragment stats.abort() is not a function and continues the loop.
Any ideas?
You are calling abort on a function. Functions do not have abort.
You want to kill the setTimeout. So you need to hold a reference to the timer.
(function () {
var timer;
function foo () {
console.log(new Date());
timer = window.setTimeout(foo,1000); //<-- store a reference to the timeout
}
function killTimer() {
if (timer) window.clearTimeout(timer);
}
}());
If you want to also abort an active Ajax request, you need to hold a reference to that too.
xhr = $.ajax(...);
...
xhr.abort();