2012-06-01 13 views
5

Quindi ho un intervallo che creo per ciascuno dei miei post, il problema è che carico nuovi post e rimuovo quelli vecchi, quindi ovviamente vorrei interrompere l'intervallo per i post precedenti. Tuttavia non riesco a capire come farlo. Qualcuno potrebbe spiegarmi come fare correttamente a fare questo? Sono completamente perso.JavaScript/jQuery clearInterval impostato in .each

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

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

$(".button").click(function(){ 
    clearInterval(myInterval); 
}); 

risposta

4

È possibile memorizzare l'ID intervallo in un attributo di dati:

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

e deselezionare l'intervallo specifico per ogni .post in questo modo:

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

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

e come SiGanteng detto, si dovrebbe passare un oggetto funzione a setInterval anziché una stringa, che ottiene solo eval 'd.

+0

+1 stavo per suggerire utilizzando una matrice - ma il 'data' proprietà è perfetta per questo – ManseUK

+0

Grazie mille. – Ian

2

è necessario mantenere una maniglia per ogni intervallo che si avvia:

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 = []; 
}); 
+0

+1 potresti usare un array associativo usando 'id' come chiave – ManseUK