Muhammad Abid
Muhammad Abid

Reputation: 11

I want to stop this function after it clicks 100 Times

I just want to stop this code after it clicks 100 times. I'm a beginning coder. I'm using the second script to work.

<form method="post" action="cashads.php" target="clk">
  <input type="hidden" name="ad_new" value="145">
  <input type="submit" id="clk" class="buttonN" style="background- 
    color:#1D03FB" value="Open Ad">

setInterval(function(){document.getElementById("clk").click();},42000);

This is second Script for stoping click after 100 times.

setTimeout(function(){ document.getElementById("clk").remove();},4200000);

Upvotes: 1

Views: 405

Answers (2)

JO3-W3B-D3V
JO3-W3B-D3V

Reputation: 2134

Explained

To make this clean and easy to read, you can see that in this solution, there's a simple counter variable, increment that for every time the button has been clicked, once the counter has reached 99 then make the onclick property set to null.

In this example, I've just made it so that it will also clear the interval variable, aka make use of clearInterval.

// Get access to the button.
const btn = document.getElementById("clk");
let counter = 0,
  interval;

// Once the button has been clicked 100 times. 
const onComplete = () => {
  btn.onclick = null;
  clearInterval(interval);
};

// Handle the click event. 
// Prints 0 - 99 (aka 100 clicks)
const clickHandler = () => {
  console.log(counter);
  counter++;
};

// Handle the on click event.
btn.onclick = () => counter >= 100 ? onComplete() : clickHandler();

// Demo 
interval = setInterval(() => {
  btn.click();
}, 0);
<input type="submit" id="clk" class="buttonN" style="background-color:#1D03FB" value="Open Ad">

Upvotes: 1

Pingolin
Pingolin

Reputation: 3417

You can use a variable i that you can increment each time you call the setInterval callback function. Once you reach your limit, just use the clearInterval function to prevent any further click.

var currentClick = 1;
// Change those values below according to your needs
var maxClick = 3; // Number of clicks
var delayClick = 1000; // Delay in milliseconds

var interval = setInterval(function() {
  console.log(currentClick);
  if (currentClick++ === maxClick) {
    clearInterval(interval);
  }
}, delayClick);

Upvotes: 1

Related Questions