JavaScript / jQuery clearInterval set to .each

So, I have an interval that I create for each of my messages, the problem is that I upload new messages and delete old ones, so obviously I would like to stop the interval for previous messages. However, I cannot figure out how to do this. Can someone explain to me how to do this right? I am completely lost.

$(".post").each(function(){
    myInterval = setInterval("postStats('"+$(this).attr('id')+"')", 500);
});

function postStats(pid) {
    //do some stuff
}

$(".button").click(function(){
    clearInterval(myInterval);
});
+5
source share
2 answers

You can save the interval identifier in the data attribute:

$(".post").each(function () {
    var that = this;
    var myInterval = setInterval(function () {
        postStats(that.id);
    }, 500);
    $(this).data("i", myInterval);
});

and clear the interval specific to each .postas follows:

$(".button").click(function () {

    // assuming the button is inside a post
    clearInterval($(this).closest(".post").data("i"));
});

and, as SiGanteng said, you should pass the object to the function setInterval, not a string that only gets eval' d.

+4

:

var myIntervals = [];

$(".post").each(function(){
  var id = $(this).attr('id');
  var handle = window.setInterval(function(){
    postStats(id);
  }, 500);
  myIntervals.push(handle);
});

function postStats(pid) {
//do some stuff
}

$(".button").click(function(){
  $.each(myIntervals, function(i, val){
    window.clearInterval(val);
  });
  myIntervals = [];
});
+2

All Articles