jQuery - clearInterval seems not to work

250 views Asked by At

Long story short: If the interval count exceeds 5 the code should clear the interval, stopping it from executing the function every second. But this doesn't seem to work.

HTML

<div id='feedback'></div>

JavaScript / jQuery

window.intervalcount = 0;

var interval = setInterval(function () {
    intervalcount += 1;
    $("#feedback").text(intervalcount);
}, 1000);

if(intervalcount > 5) {
    clearInterval(interval);
}

But I can't seem to find the issue...

3

There are 3 answers

0
Phil Barresi On BEST ANSWER

So currently, your code is going to run something like this order:

window.intervalcount = 0;

// Interval is defined here
var interval = setInterval(function () {
    intervalcount += 1;
    $("#feedback").text(intervalcount);
}, 1000);

// will be 0 still
if(intervalcount > 5) {
    clearInterval(interval);
}

// 1 second after the interval is defined:
    intervalcount += 1; // now equals 1
    $("#feedback").text(intervalcount);

// 2 seconds after defined:

    intervalcount += 1; // now equals 2
    $("#feedback").text(intervalcount);

// etc, forever

Placing the:

if(intervalcount > 5) {
    clearInterval(interval);
}

inside the interval's function will perform your desired behavior.

1
AmmarCSE On

You need the if inside the callback itself like

window.intervalcount = 0;

var interval = setInterval(function () {
    intervalcount += 1;
    $("#feedback").text(intervalcount);
    if(intervalcount > 5) {
        clearInterval(interval);
    }
}, 1000);

This is because your code will not execute in a sequential manner. Rather, that if will execute before any of the intervals execute because they are executed later

1
VoteyDisciple On

You're trying to execute the clearInterval() immediately after setting it. That happens before any seconds have elapsed. First you set the interval, then you check if any have elapsed (they haven't) then five seconds later it would be time to clear the interval — but by then it's already run.

Perhaps you meant to check during the execution each time?

var interval = setInterval(function () {
    if(intervalcount > 5) {
        clearInterval(interval);
    } else {
        intervalcount += 1;
        $("#feedback").text(intervalcount);
    }
}, 1000);