简体   繁体   中英

How can I click 'mybutton' every 10 seconds?

function startTimer(){
  timeticker=1s;
  document.getElementById('mybuttonn');
  time = 0;
  while (time%10==0){
    mybuttonn.click();
    time += timeticker;
  }
}
const timer = setInterval(() => {
  document.getElementById('mybuttonn').click();
}, 10000);

When you want to stop call clearInterval(timer)

You can shrink down your function to:

function startTimer(){
    var button = document.getElementById('mybuttonn');
    button.click();
}

Then call it in an interval function

setInterval(startTimer(), 10000);

And you should wrap this in a DOMContentLoaded event:

document.addEventListener("DOMContentLoaded", function(){
    setInterval(startTimer(), 10000);
});

The interval value "10000" is in milliseconds

I think setInterval() is better fit here:

 var mybuttonn = document.getElementById('mybuttonn'); mybuttonn.addEventListener('click', function(){ console.log('button clicked'); }); var f = function() { mybuttonn.click(); }; f();//execute the function on page load window.setInterval(f, 10000); //pass the function and time in milliseconds
 <button id="mybuttonn">Button</button>

Try with the following, It works fine:-

 let clicks = 0; function addClick() { clicks = clicks + 1; document.querySelector('.total-clicks').textContent = clicks; } // Simulate click function function clickButton() { document.querySelector('#btn1').click(); } // Simulate a click every second setInterval(clickButton, 10000);
 <p> The button was clicked <span class="total-clicks"></span> times </p> <button id="btn1" onclick="addClick()"> Click Me! </button>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM