Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

493
Views
Why clearInterval doesn't work if the setInterval was inside the function?
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.

about 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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.

about 4 years ago · Santiago Trujillo Report

0

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();
about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!