JavaScript/jQuery clearInterval being set in .each
Asked Answered
R

2

5

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);
});
Romaromagna answered 1/6, 2012 at 9:56 Comment(0)
A
5

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.

Amelioration answered 1/6, 2012 at 10:0 Comment(1)
+1 i was going to suggest using an array - but the data property is perfect for thisFremitus
D
2

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 = [];
});
Dieppe answered 1/6, 2012 at 10:2 Comment(1)
+1 you could use an associative array using the id as a keyFremitus

© 2022 - 2024 — McMap. All rights reserved.