1

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);
  • 1
    How about maintaining a counter for that ? – Rayon Jan 02 '19 at 13:00
  • 2
    Instead of `document.getElementById("clk").remove()` try removing the interval itself. Try `var interval = setInterval(...)` and then `window.clearInterval(interval)` – Rajesh Jan 02 '19 at 13:00
  • 2
    Reading [the documentation](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval) is always helpful. – Teemu Jan 02 '19 at 13:01
  • Possible duplicate of [Stop setInterval call in JavaScript](https://stackoverflow.com/questions/109086/stop-setinterval-call-in-javascript) – Nino Filiu Jan 02 '19 at 13:20

2 Answers2

1

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);
Pingolin
  • 3,161
  • 6
  • 25
  • 40
1

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">
JO3-W3B-D3V
  • 2,124
  • 11
  • 30