skip to Main Content

I have a script

<input type="text" value="0" id="count_id">

<input type="button" value="Click Me" id="button_id" onclick="myFunction()">

<script>
function myFunction() {
    
    var data = document.getElementById("count_id").value;
    var  datacount = (parseInt(data) + 1);
    document.getElementById("count_id").value = datacount;  
    document.getElementById("button_id").value = "Clicked";
    
}
setInterval(function(){
document.getElementById("button_id").click();   
}, 3000);
}
</script>

by using this they click on button every 3 seconds

I want they click on button only 2 time then stop but they click again again and again

Help me here

2

Answers


  1. You can make a counter and check the condition by the counter value and if the button is clicked 2 times then you can clear the intervak

    <input type="text" value="0" id="count_id">
    
    <input type="button" value="Click Me" id="button_id" onclick="myFunction()">
    
    <script>
    let count = 0;
    function myFunction() {
        
        var data = document.getElementById("count_id").value;
        var  datacount = (parseInt(data) + 1);
        if(count < 2){
            document.getElementById("count_id").value = datacount;  
            document.getElementById("button_id").value = "Clicked";
            count ++;
        }
    }
    
    setInterval(function(){
        if(count < 2){
            document.getElementById("button_id").click();   
         }
         else {
           clearInterval()
        }
    }, 3000);
    
    </script>
    Login or Signup to reply.
  2. You would need a variable to count the number of clicks. Here’s an example:

    // the x variable counts the number of clicks
    let x = 0;
    
    function myFunction() {
        var data = document.getElementById("count_id").value;
        var  datacount = (parseInt(data) + 1);
     // only run this code if the button hasn't been clicked more than twice
        if (x < 2) { 
        document.getElementById("count_id").value = datacount;
        document.getElementById("button_id").value = "Clicked";
        }
    }
    setInterval(function(){
        if (x < 2) {
            document.getElementById("button_id").click();
            x++; // increase x for every click
        }
        else clearInterval(); // clear the loop when x is 2 or more
    }, 3000);
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search