Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

233
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda