简体   繁体   中英

clearInterval doesn't work

I have problems with my clearInterval, It doesn't stop my setInterval, here is code:

$(".auto-check").click(function(){
    if($('input[name=autorefresh]').is(':checked') == true){
        var intervalId = setInterval(load,4000);

    }
    else{
        alert("Auto Refresh is off");
        clearInterval(intervalId);
    }

}); 

who can tell, where is problem?

Just for the sake of argument, an alternate approach using jQuery .data()

$(".auto-check").click(function(){
    var elem = $('input[name=autorefresh]'
    if(elem.is(':checked')){
        elem.data("interval-id", setInterval(load,4000));
    }
    else{
        alert("Auto Refresh is off");
        clearInterval(elem.data("interval-id"));
        elem.removeData("interval-id");
    }
}); 

You need to keep the intervalId. In your case, you declare it locally, and it is lost after the function. Declare it outside the function, define it inside, then it will be valid.

var intervalId;

$(".auto-check").click(function(){
if($('input[name=autorefresh]').is(':checked') == true){
    intervalId = setInterval(load,4000);

}
else{
    alert("Auto Refresh is off");
    clearInterval(intervalId);
}

}); 

what about this?

$(".auto-check").click(function(){
if($('input[name=autorefresh]').is(':checked') == true){
    window.intervalId = setInterval(load,4000);

}
else{
    alert("Auto Refresh is off");
    clearInterval(window.intervalId);
}

});

Try this:

var intervalId = null;

$('.auto-check').click(function(){
 if($('input[name=autorefresh]').is(':checked') == true) {
   intervalId = setInterval(load,4000);
 } else {
   alert('Auto Refresh is off');
   clearInterval(intervalId);
 }
});

As others have noted, you need the scope of your interval object to be greater than the scope of the function in which it is enclosed, as the next time you click the element(s) a new callback function will be created with an entirely new scope; your interval will be an entirely new object with each click.

EDIT: while a long video, here is a detailed explanation of scope chains and execution contexts, detailing exactly what happens when a function is executed. Explanation starts roughly 5 minutes in: http://googlecode.blogspot.com/2009/06/nicholas-c-zakas-speed-up-your.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM