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);
CodePudding user response:
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);
CodePudding user response:
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>