简体   繁体   中英

Can't stop setInterval with clearInterval

Been playing with this in a fiddle for 4 hours now and cant find a solution...

HTML:

Real Time Data: <input type="checkbox" id="dataStream"/>

js:

var chartInt = null;
$("#dataStream").change(function() {
    if(this.checked) {
        var chartInt = setInterval(function() { alert('checked') }, 7000);
    } else {
        clearInterval(chartInt);
        chartInt = null;
        alert('unchecked');
    }
});

Note: because clearInterval is not working you need to click on "run" in the jsfiddle to get it to stop after clicking the checkbox, you have 7 seconds between alerts...

Here is a link to the jsfiddle: http://jsfiddle.net/5udtC/5966/

Thanks!

Don't redefine the variable in the local scope

var chartInt = null;
$("#dataStream").change(function() {
    if(this.checked) {
        chartInt = setInterval(function() {  // no "var" here
            alert('checked') 
        }, 7000);
    } else {
        clearInterval(chartInt);
        alert('unchecked');
    }
});

for new Searchers that came up with same issue. Have A look on this link it worked for me perfectly, specially if you have multiple timers and you need to clearInterval from another js file as in my case.

When you set an interval, you get a pointer to it:

var myInterval = setInterval(function() {}, 4000);

If you want to cancel an interval, you do the following:

clearInterval(myInterval);

So, for what you want to do, you would do the following:

var intervals = [];
$(".elements").each(function() {
   var i = setInterval(function() {

   }, 1000);
   intervals.push(i);
});

Then if you need to cancel them all you can do this:

intervals.forEach(clearInterval);

You also need to take in consideration JS files call order in your html for the function to defined before calling.

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