Why does clearInterval not work if setInterval is inside a function?

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

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

consoleTest();

I created a simple application, when I press the button, it stops / pauses the interval. I know how to make it work. I just need to declare a variable outside the function and contain setInterval there, now I'm just confused why clearInterval will not work if I call it through the function, someone please explain this to me.

+4
source share
2 answers

setInterval cleaInterval. setInterval , , . , clearInterval :

var interval;

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

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

consoleTest();

: clearInterval setInterval.

+5

. -, setInterval() . consoleTest - , , , clearInterval(). -, , . , :

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

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

var interval = consoleTest();
+1

Source: https://habr.com/ru/post/1671860/


All Articles