If you want to display the current time, then the previous example is need to be extended a bit. But before it let’s create a JavaScript function which displays the actual time in the format HH:mm:ss, eg.: 22:45:03. To do this we can use the following function:

      function showTime(){

      myDate = new Date();

      // Get time parts

      hours = myDate.getHours();

      minutes = myDate.getMinutes();

      seconds = myDate.getSeconds();

      // Just to display the time in a nice format

      if (hours < 10) hours = "0" + hours;

      if (minutes < 10) minutes = "0" + minutes;

      if (seconds < 10) seconds = "0" + seconds;

      actualTime = hours+":"+minutes+":"+seconds;


Before setting up a timeout event we need to define a location where to put the current time value. To do this just make a named block in your html code just like this:

      <p>The actual time is:<span id="actTime"></span></p>

Here we have the span block with an id actTime. With this information we can edit the content of the span tag from your JavaScript code as follows:

      document.getElementById("actTime").innerHTML = actualTime;

Ok, now it’s time to make the interesting thing. We also have 2 buttons here. The first starts the clock and the second will stop it. It means that we need an other function to stop the timer. Let’s call it to endTime(). So our html code looks like this at the moment:


      <p>The actual time is:<span id="actTime"></span></p>

      <button onclick="showTime();">Start clock</button>

      <button onclick="endTime();">Stop clock</button>


However we need to extend the JavaScript part. First of all we need to add the timeout function at the end of our showTime() function in the following form:

      myTimer = setTimeout("showTime()",1000);

Please not that we stored the return value in a global variable declared outside of the function. Using this variable we can stop the timer in the endTime() function as here:

      function endTime(){



That’s all. Now you have the current time displayed on your page.

Republished by Blog Post Promoter