1

How can you make a live clock in 00:00 format? I've included my code down below. Is there a way to do this better or with shorter code?

HTML

<body onload=display_ct();>
<span id='ct'></span>

Now we just need to add the javascript part. This refreshes the clock every second so its "Live". Also it uses functions like getMinutes to fetch the current time.

Javascript

function display_c(){
var refresh=1000; // Refresh rate in milli seconds
mytime=setTimeout('display_ct()',refresh)
}
function display_ct() {
var x = new Date()
x1 = x.getHours( )+ ":" +  x.getMinutes();
document.getElementById('ct').innerHTML = x1;
display_c();
 }

The 1000 milliseconds can be swapped out with more or less. 1000 is equal to 1 second so that would mean 500ms would be .5 seconds.

I'll include my code in an executable here:

function display_c(){
var refresh=1000; // Refresh rate in milli seconds
mytime=setTimeout('display_ct()',refresh)
}
function display_ct() {
var x = new Date()
x1 = x.getHours( )+ ":" +  x.getMinutes();
document.getElementById('ct').innerHTML = x1;
display_c();
 }
<body onload=display_ct();>
<span id='ct'></span>
Liam
  • 22,818
  • 25
  • 93
  • 157
Mark dG
  • 173
  • 12

2 Answers2

3

You need to use setInterval instead of setTimeout. Additionally you can use padStart() function to add leading zeros to your string values.

Ps: Because you are only showing hours and minutes, the clock will be updated every minute, instead of every seconds.(function still runs every second)

function display_c() {
  var refresh = 1000; // Refresh rate in milli seconds
  mytime = setInterval(display_ct, refresh)
}

function display_ct() {
  var x = new Date()
  x1 = x.getHours().toString().padStart(2,0) + ":" + x.getMinutes().toString().padStart(2,0);
  document.getElementById('ct').innerHTML = x1;
  display_c();
}
<body onload=display_ct();>
  <span id='ct'></span>
firatozcevahir
  • 770
  • 2
  • 10
1

make a js inside or out your main page like this

You must have an element with MyClockDisplay as id for this code

    function showTime() {
        var date = new Date();
        var h = date.getHours(); // 0 - 23
        var m = date.getMinutes(); // 0 - 59
        var s = date.getSeconds(); // 0 - 59
        var session = "AM";
        if (h == 0) {
            h = 12;
        }
        if (h > 12) {
            h = h - 12;
            session = "PM";
        }
        h = h < 10 ? "0" + h : h;
        m = m < 10 ? "0" + m : m;
        s = s < 10 ? "0" + s : s;
        var time = h + ":" + m + ":" + s + " " + session;
        document.getElementById("MyClockDisplay").innerText = time;
        document.getElementById("MyClockDisplay").textContent = time;
        setTimeout(showTime, 1000);
    }
    showTime();
<div id="MyClockDisplay"></div>
kernel
  • 11
  • 2