Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why clearInterval doesn't work if the setInterval was inside the function? [duplicate]

function consoleTest() {
    setInterval(function(){
     console.log('Hello World');
    }, 1000);
}

$('#button').on('click', function(){
    clearInterval(consoleTest);
});

consoleTest();

I created a simple app when I click the button it will stop/pause the interval. I know how to make it work I just need to declare a variable outside the function and contain there the setInterval, now I am just confused why clearInterval won't work if I call it via a function, somebody please explain it to me.

like image 567
Ron Avatar asked Feb 05 '23 22:02

Ron


2 Answers

This is the correct usage of setInterval and cleaInterval. setInterval returnes a value which you need to keep in a variable scoped for both function. When you want to clear the interval, use clearInterval and pass it the variable as a parameter:

var interval;

function consoleTest() {
    interval = setInterval(function() {
        console.log('Hello World');
    }, 1000);
}

$('#button').on('click', function() {
    clearInterval(interval);
});

consoleTest();

For further reading: clearInterval and setInterval.

like image 75
Koby Douek Avatar answered Feb 07 '23 11:02

Koby Douek


There's two issues here. Firstly you don't set the returned timer id from setInterval() anywhere. consoleTest is the function that wraps the timer, not a reference to the timer, which is what should be given to clearInterval(). Secondly, you need that timer reference to be in scope of both functions. With that in mind, try this:

function consoleTest() {
  return setInterval(function(){
    console.log('Hello World');
  }, 1000);
}

$('#button').on('click', function(){
  clearInterval(interval);
});

var interval = consoleTest();
like image 27
Rory McCrossan Avatar answered Feb 07 '23 12:02

Rory McCrossan