artist artist - 2 months ago 7
HTML Question

Number of times button is clicked

I am counting the times the button is clicked but on the third time I want to exit from the function. In my code it's not exiting after the third click. Any ideas?
Thanks
In the html page;

<button onclick="myFunction()">Try it</button>



<script>
var count = 0;

function myFunction(){

count = count + 1;
alert(count);

if(count == 3){
//exit the function but it's not doing that and keeps on counting.
return;
}

}
</script>

Answer

Move the conditional above the alert. Every time the button is clicked, you're calling the function, which alerts the count before it checks the whether it should return.

<button onclick="myFunction()">Try it</button>



 <script>
       var count = 0;

       function myFunction(){

           if(count == 3){
               //exit the function but it's not doing that and keeps on counting.
               return;
            }
            count = count + 1;
            alert(count);  
        }
</script>