Cancel event queue in Javascript / Jquery

2
So, I have a loop that will awaken some 10 functions that are AJAX requests, in functions, which encompasses AJAX requests is a setTimeout() , what happens is that the loop is executed on time, and every time 10 seconds (as I have determined in setTimeout() ) a function is executed ..

But if I want to abort all functions (which have already been called, they are only waiting for the time to execute, as I determined in setTimeout ), what could I do?

My code is + - like this:

$("array").each(function(i){
 setTimeout(function(){
  $.ajax({..});
 },5000*i);

});
    
asked by anonymous 26.03.2015 / 19:46

1 answer

3

I suggest you take another approach. You put an AJAX call starting the other one within your success function. This way, it does not generate excess calls.

In what way and by responding to your problem you can do this:

var chamadas = {};
$("array").each(function (i) {
    chamadas[i] = setTimeout(function () {
        alert('AJAX!');
    }, 5000 * i);
});

// e quando precisares de cancelar
for (var nr in chamadas){
    clearTimeout(chamadas[nr]);
};

// ou se quiseres cancelar uma específica 
clearTimeout(chamadas[3]);
    
26.03.2015 / 20:05