Dragan
Dragan

Reputation: 67

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

Upvotes: 1

Views: 912

Answers (4)

user6269972
user6269972

Reputation: 319

const timer = setInterval(() => {
  document.getElementById('mybuttonn').click();
}, 10000);

When you want to stop call clearInterval(timer)

Upvotes: 1

Mehadi Hassan
Mehadi Hassan

Reputation: 1220

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> 
      
 

Upvotes: 0

Mamun
Mamun

Reputation: 68933

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>

Upvotes: 0

Cypherjac
Cypherjac

Reputation: 879

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

Upvotes: 0

Related Questions