Core JavaScript

Clock

The function setInterval() provides a way of setting a function that is called at regular time intervals. The arguments are the function to be called and the number of milliseconds that should elapse between calls. When the setInterval() function is called, it passes back an integer that is the id if the timer. This can be passed into the clearInterval() function to stop the timed function calls.

Below, we make use of this function to create a simple clock that we can start and stop by pressing the corresponding buttons. To stop the setInterval() function, we make a call to clearInterval() and pass in the id of the timer that we wish to stop.

Clock.html

<!DOCTYPE html>
<html>
  <head>
    <title>XoaX.net's JavaScript: A Time Interval Clock with Stop and Start Buttons</title>
    <script type="text/javascript">
      var iCurrTimerID = 0;
      var bHasStarted = false;

      function SetTime() {
        var qDate = new Date();
        var sTime = qDate.toLocaleTimeString();
        document.getElementById("time").innerHTML = "Time: " + sTime;
      }
      // Start a new timer if one is not already running.
      function Start() {
        if (!bHasStarted) {
          iCurrTimeID = setInterval(SetTime, 1000);
          document.getElementById("timer_id").innerHTML = "Timer ID: " + iCurrTimerID;
          bHasStarted = true;
        }
      }
      // Stop the timer if one is alrady running.
      function Stop() {
        if (bHasStarted) {
          // Stop the current timer.
          clearInterval(iCurrTimerID);
          bHasStarted = false;
        }
      }
    </script>
  </head>
  <body>
    <p id="timer_id">Timer ID: </p>
    <p id="time">Time: </p>
    <button onclick="Start()">Start</button>
    <button onclick="Stop()">Stop</button>
  </body>
</html>
 

Output

 
 

© 2007–2024 XoaX.net LLC. All rights reserved.