Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

492
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda