Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript/jQuery clearInterval being set in .each

So I have an interval I create for each of my posts, the issue is that I load new posts and remove the old ones, so obviously I'd like to stop the interval for the previous posts. However I can't seem to figure out how to do this. Could someone explain to me how to properly go about doing this? I'm completely lost.

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

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

$(".button").click(function(){
    clearInterval(myInterval);
});
like image 865
Ian Avatar asked Jun 01 '12 09:06

Ian


2 Answers

You can store the interval ID in a 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 .post like so:

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

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

and like SiGanteng said, you should pass a function object to setInterval rather than a string, which only gets eval'd.

like image 100
karim79 Avatar answered Oct 12 '22 15:10

karim79


You need to keep one handle for each interval that you start:

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 = [];
});
like image 20
Guffa Avatar answered Oct 12 '22 15:10

Guffa