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

232
Views
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 answers
Answer question

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 Report

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