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

103
Vistas
How to stop setInterval with javasript?

I want to start from 0. Until it reaches the numbers 709 and 54, Stop it.

HTML

<span class="card-title h5 counter"> 709 + </span>
<span class="card-title h5 counter"> 54+ </span>

script.js

let intervals = [];
let counter  = [];
let elements = document.getElementsByClassName('counter');
Array.from(elements).forEach((element, index) => {
    counter[index] = 0;
    intervals[index] = setInterval(()=> {
            counter[index]++;
            element.innerText=counter;
        }
        , 50);
})

But this code goes on indefinitely and does not end.

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

this way...

use the same setInterval for both, and clear it when there is no more counter to increment.

const elements = [...document.querySelectorAll('.counter')].map(el=>({el,counter:parseInt(el.textContent), val:-1}))

let intervalReference = setInterval(() => 
  {
  let endingCount = 0 
  elements.forEach(refs =>
    {
    if ( refs.val < refs.counter) 
      refs.el.textContent = ` ${++refs.val} + `
    else 
      ++endingCount
    })
  if (endingCount===elements.length) clearInterval(intervalReference)
  }, 50)
  <span class="card-title h5 counter"> 709 + </span>
  <span class="card-title h5 counter"> 54+ </span>

about 4 years ago · Juan Pablo Isaza Denunciar

0

You can also do it in two separate setInterval() calls. Each one is defined within their own scope. This way there is no need to set up arrays for storing the values and references outside the scope:

[...document.querySelectorAll('.counter')]
.forEach(e=>{ let i=0;
  const n=parseInt(e.textContent),
     h=setInterval(()=>{
       if(i<n) e.textContent=++i +" + ";
       else    clearInterval(h);
     },20)
});
<span class="card-title h5 counter"> 709 + </span>
<span class="card-title h5 counter"> 54 + </span>

about 4 years ago · Juan Pablo Isaza 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