1

every 5 seconds with setTimeout I'm executing a jQuery function, how can I stop the process by clicking on a div?

my code is:

function crono(selection){
    $.ajax({
        type: 'GET', 
        url: 'my_page.php', 
        data: {
            my_page: selection.attr('id')
        },
        success: function(data, textStatus, jqXHR) {
            selection.html(data);   
        }
    });
}


function repeat(){
    setTimeout(function() {
        $('.toReload').each(function(){
            crono($(this));
        });
        repeat();
    }, 5000);
}

repeat();
user2461031
  • 513
  • 2
  • 7
  • 17

5 Answers5

1

Use clearTimeout https://developer.mozilla.org/fr/docs/DOM/window.clearTimeout :

var handle = null;

function repeat(){
    handle  = setTimeout(function() {
        $('.toReload').each(function(){
            crono($(this));
        });
        repeat();
    }, 5000);
}

and cancel the setTimeout by calling :

clearTimeout(handle);
sdespont
  • 13,915
  • 9
  • 56
  • 97
1

Use flag to do this.

var end = false;

function repeat(){
   setTimeout(function() {
      if(!end){ 
          $('.toReload').each(function(){
            crono($(this));
          });
          repeat();
      }     
   }, 5000);
}
...

$('#div').click(function(){
 end = true;
});
Damian0o
  • 653
  • 5
  • 15
0

Use the timeout ID.

var timeoutID = 0;
function repeat(){
     timeoutID = setTimeout(function() {
        $('.toReload').each(function(){
            crono($(this));
        });
        repeat();
    }, 5000);
}

repeat();

//stop the time out
clearTimeout(timeoutID);
Eric Frick
  • 847
  • 1
  • 7
  • 18
0

Use the clearTimeout function

var timeout;

function repeat(){
    timeout = setTimeout(function() {
        $('.toReload').each(function(){
            crono($(this));
        });
        repeat();
    }, 5000);
}

and on the div click call the following function

function stopAjax(){
    clearTimeout(timeout);
}
Sherin Jose
  • 2,508
  • 3
  • 18
  • 39
0

You need clear timeout and ajax request:

    var getData = {
    handleTimeout : 0,
    handleAjax,

    crono : function(selection){
        $.ajax({
            type: 'GET', 
            url: 'my_page.php', 
            data: {
                my_page: selection.attr('id')
            },
            success: function(data, textStatus, jqXHR) {
                selection.html(data);   
            }
        });
    },

    repeat: function(){
        this = ob;
        this.handleTimeout = setTimeout(function() {
            $('.toReload').each(function(){
                ob.crono($(this));
            });
            repeat();
        }, 5000);
    },

    stopAll: function(){
        clearTimeout(this.handleInterval);
        this.handleAjax.abort();
    }
}

getData.repeat();
getData.stopAll();
e-info128
  • 3,727
  • 10
  • 40
  • 57