Create a simple click counter using JavaScript

Create a simple click counter using JavaScript

The counter is a frequent function of games and various applications programmed in javascript. In a way, it is also the basis applicable to slideshows and other roundabouts.

In the following example, we use the Jquery library knowing that the code could very well be produced without using it.

The principle is as follows:

  • We define 4 parts in our HTML page allowing us to display and manipulate the counter (start, stop, reset).

  • In the JavaScript we define the variables and functions for each button. From there, the Chrono function will be called at each interval of the counter (here every second) and will make it possible to test the state of the counter to adapt the display.

<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
  <div id="timer">00 : 00</div>
  <div id="play">></div>
  <div id="pause">||</div>
  <div id="reset">reset</div>
</body>
</html>

$(document).ready(function(){
  var secondes = 0;
  var minutes = 0;
  var on = false;
  var reset = false;

  $("#play").click(function(){
    Start();
  });
  $("#pause").click(function(){
    Stop();
  });
  $("#reset").click(function(){
    Reset();
  });

function chrono(){
    secondes += 1;

    if(secondes>59){
      minutes += 1;
      secondes = 0;
    }

    if(minutes<10 && secondes<10){
      $("#timer").html("0"+minutes+" : 0"+secondes);
    }
      else if(minutes<10 && secondes>=10){
        $("#timer").html("0"+minutes+" : "+secondes);
    }
    else if(minutes>=10 && secondes<10){
        $("#timer").html(+minutes+" : 0"+secondes);
    }
    else if(minutes>=10 && secondes>10){
        $("#timer").html(+minutes+" : "+secondes);
    }
  }

  function Start(){
    if(on===false){
      timerID = setInterval(chrono, 1000);
      on = true;
      reset = false;
    }
  }

  function Stop(){
    if(on===true){
      on = false;
      clearTimeout(timerID);
    }
  }

  function Reset(){
    if(reset===false)
    {
      clearInterval(timerID);
      secondes = 0;
      minutes = 0;
      $("#timer").html("00 : 00");
      reset = true;
    }
  }

});