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

234
Vistas
Set time interval every 2 seconds and stop at 10 seconds for button click

I am trying to automatically click a button every 2 seconds, but i want it to stop at for example 10 seconds. I tried the following, but after the 10 seconds it just continues.

Please could you assist where i am going wrong?

// repeat with the interval of 2 seconds
let timerId = setInterval(() => document.getElementById("somebutton").click(), 2000);

// after 10 seconds stop
setTimeout(() => { clearInterval(timerId); alert('stop');}, 10000);
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Instead of doing this by creating and clearing intervals, one way to accomplish this would be to explicitly perform your action in a loop.

For example:

async function repeat(handler, interval, times) {
  for (let i = 0; i < times; i++) {
    handler();
    await new Promise((res) => setTimeout(res, interval));
  }
}

repeat(() => {
  document.getElementById("somebutton").click()
}, 2000, 10 / 2);
about 4 years ago · Juan Pablo Isaza Denunciar

0

Let's assume, we have a button as shown below.

Then, let's get the button into javascript.

Then let's write the logic for the button is clicked every 2 seconds and after the 10 seconds, setInterval execution stops.

So, let's take a variable timesClicked, which keeps the count of the button is clicked, and increments every time the button is clicked.

Now, since the interval is 2 seconds and the button will be clicked 5 times during 10 seconds, so once the timesClicked value equals 5, we should clear the setInterval function.

let button = document.getElementById("button");
button.onclick = function () {
  console.log("Button Clicked!");
};
// the timesClicked will have the number of times the button is clicked or setInterval is executed
let timesClicked = 0;

let interval = setInterval(function () {
  // after 10 seconds or after 5 times the setInterval should stop executing
  if (timesClicked == 5) {
    clearInterval(interval);
  }
  button.click();
  timesClicked++;
}, 2000);
<button id="button">Click Me!</button>

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