Cancel Javascript/Jquery event queue

Asked

Viewed 354 times

2

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

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

My code is +- like this:

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

});

1 answer

3


I suggest you take a different approach. Put one AJAX call to start the other one inside its success Function. This way does not generate excess calls.

However and responding to your problem you can do so:

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]);
  • thanks for the reply and the suggestion, only left a doubt now, will the to pause the setTimeout? Regarding the suggestion, I will apply next time what they call Promises and deferred, for me it is still a little confusing, but when I apply maybe uncomplicate once and for all..

  • 1

    @Alexandrec.Caus can not pause the setTimeout. You can have a counter in a variable that is checked by a clock setInterval and this check has a flag pause / play. Something like this: https://jsfiddle.net/5ntqc993/

  • perfect @Sergio, liked the example, I’ll end up implementing something like this in my application! hugs and success.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.