Search code examples
javascriptbuttononclickclicklimit

How do I limit the number of clicks on a button in JavaScript?


I need to display the button Hour, 2 numbers in big font 0:0, and a button Minute.

The first number represents the hour, the second number represents the minute.

Whenever the user clicks the Hour button, the first number is increased by 1, so that it goes like 0, 1, 2, 3, …, 23.

If the hour number is 23 and the user clicks the hour button then the number goes back to 0.

Similarly, whenever the user clicks the “Minute” button, the second number is increased by 1, so that it goes like 0, 1, 2, 3, …, 59. If the minute number is 59 and the user clicks the minute button then the number goes back to 0.

Here's what I have done so far.

<table>
<tr>
<td>
  <button onclick="displaycount()">Hour </button>
</td>
<td>
  <p id="carrier"> 0 </p>
</td>
<td>
  :
</td>
<td>
  <p id="carrier2"> 0 </p>
</td>
<td>
  <button onclick="displaycount2()">Minute </button>
</td>


</tr>
</table>

<script>
var count =(function() {
var counter = 0;
return function() {return counter +=1;}
})();

var count2 =(function() {
var counter = 0;
return function() {return counter +=1;}
})();

function displaycount(){
document.getElementById("carrier").innerHTML = count();
}

function displaycount2(){
document.getElementById("carrier2").innerHTML = count2();
}
</script>

Solution

  • You can use modulus (%) to reset the counter back to 0 for hours and minutes:

    var count = (function() {
        var counter = 0;
        return function() {
          return counter = (counter + 1) % 24;
        }
      })();
    
    var count2 = (function() {
      var counter = 0;
      return function() {
        return counter = (counter + 1) % 60;
      }
    })();
    
    function displaycount() {
      document.getElementById("carrier").innerHTML = count();
    }
    
    function displaycount2() {
      document.getElementById("carrier2").innerHTML = count2();
    }
    <table>
      <tr>
        <td>
          <button onclick="displaycount()">Hour </button>
        </td>
        <td>
          <p id="carrier"> 0 </p>
        </td>
        <td>
          :
        </td>
        <td>
          <p id="carrier2"> 0 </p>
        </td>
        <td>
          <button onclick="displaycount2()">Minute </button>
        </td>
    
    
      </tr>
    </table>