clearInterval not working with setInterval
-
02-03-2021 - |
Pergunta
I have a problem with the code below. Basically im implementing a polling mechanism, but when it is supposed to stop polling it just continues to poll. Polling infinite.
Is there any other way to force it to stop?
The function SearchPoll is only called once.
function SearchPoll(){
var i = setInterval(function ()
{
var url = "Search.aspx?polling=true";
$.ajax(
{
url: url,
success: function (data)
{
clearInterval(i);
},
error: function ()
{
clearInterval(i);
}
});
}, 1000);
}
Solução
If you want to kill all requests you need to work with the XMLHTTPRequest object returned from $.ajax. Here is an example:
function SearchPool(){
var xhrArray = [],
interval = setInterval(function () {
var url = "Search.aspx?polling=true";
xhrArray.push($.ajax({
url: url,
success: function (data) {
for(var i = 0; i < xhrArray.length; i+= 1) {
xhrArray[i].abort();
}
clearInterval(interval);
},
error: function () {
clearInterval(interval);
}
}));
}, 20);
}
SearchPool();
Outras dicas
This fiddle seems to work correctly... http://jsfiddle.net/sramam/yZTAK/
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow