4
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.

Alexander O'Mara
  • 58,688
  • 18
  • 163
  • 171
Ron
  • 41
  • 1
  • 3

2 Answers2

6

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.

Koby Douek
  • 16,156
  • 19
  • 74
  • 103
2

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();
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339