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

241
Views
Establezca un intervalo de tiempo cada 2 segundos y deténgase a los 10 segundos para hacer clic en el botón

Estoy tratando de hacer clic automáticamente en un botón cada 2 segundos, pero quiero que se detenga, por ejemplo, en 10 segundos. Intenté lo siguiente, pero después de los 10 segundos simplemente continúa.

Por favor, ¿podría ayudarme donde me estoy equivocando?

 // 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 answers
Answer question

0

En lugar de hacer esto creando y borrando intervalos, una forma de lograr esto sería realizar explícitamente su acción en un bucle.

Por ejemplo:

 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 Report

0

Supongamos que tenemos un botón como se muestra a continuación.

Luego, pongamos el botón en javascript.

Luego, escribamos la lógica para que se haga clic en el botón cada 2 segundos y después de los 10 segundos, la ejecución de setInterval se detiene.

Por lo tanto, tomemos una variable timesClicked, que mantiene el recuento de clics en el botón y aumenta cada vez que se hace clic en el botón.

Ahora, dado que el intervalo es de 2 segundos y se hará clic en el botón 5 veces durante 10 segundos, una vez que el valor de timesClicked sea igual a 5, debemos borrar la función setInterval.

 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 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!