Question

When my AJAX call is completed I need to call setInterval, but when two AJAX calls are made it also calls setInterval twice. How can I stop the previous setInterval?

$(document).ajaxComplete(function () {
  $(".iframeFake").load(function () {
    var islem = setInterval(function () {
       $('.iframeFake').each(function (event) {
         console.log(1);
       }, 1000);
   });
});

In chrome console in first post i get 1 per second - but after second post i get double 1 per second. Where is my problem?

Was it helpful?

Solution

 var islem;
 $(document).ajaxComplete(function () {
    $(".iframeFake").load(function () {
        clearInterval(islem);
        islem = setInterval(function () {
            $('.iframeFake').each(function (event) {
                console.log(1);
            }, 1000);
        });
    });

If you want to maintain that there is always one interval, store the variable at a higher scope, and cancel before you create to stop any lingering intervals.

DEMO of the principle in action

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top