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);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);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>