2

I have made a clock in javascript but its a static clock. What changes I need to do in the following code so that it updates with every second.

<html>
<head>
    <title>Javascript Clock</title>
    <script type="text/javascript">
        function clk() {
            var a=new Date();   
            document.getElementById("disp").innerHTML=a.getHours() + ":" + a.getMinutes() + ":" + a.getSeconds() ;

        }
    </script>
</head>

<body>
    <input type="button" onclick="clk()" value="Display Clock" />
    <p id="disp">Clock Space</p>
</body>

</html>
sandbox
  • 2,631
  • 9
  • 33
  • 39
  • 7
    Have a look at [`setInterval`](https://developer.mozilla.org/en/DOM/window.setInterval): `window.onload = function(){setInterval(clk, 1000);}};` – Rob W Feb 12 '12 at 10:10
  • @RobW What does `1000` relate to? – sandbox Feb 12 '12 at 10:12
  • His comment contains a link to documentation on `setInterval`, which answers your question. – Michelle Tilley Feb 12 '12 at 10:13
  • 1
    @sandbox `1000` = 1000 milliseconds = 1 second. Basically, it runs the function every second. – Rob W Feb 12 '12 at 10:14
  • @RobW. Should have been an answer... – gdoron Feb 12 '12 at 10:16
  • @gdoron: Heh, I swear I didn't see Rob's comment before I posted! – Twisol Feb 12 '12 at 10:18
  • @gdoron I know, but this question is so trivial that I feel bad for putting up the message in a comment, and getting upvotes for it. I'd rather find a duplicate, and close it for "Exact duplicate". – Rob W Feb 12 '12 at 10:18
  • @RobW. But you didn't find any? =) – gdoron Feb 12 '12 at 10:20
  • @RobW: How's this for a duplicate? http://stackoverflow.com/questions/6774027/setinterval-for-an-analogue-clock – Twisol Feb 12 '12 at 10:20
  • possible duplicate of [How to create a JQuery Clock / Timer](http://stackoverflow.com/questions/2604450/how-to-create-a-jquery-clock-timer) – Rob W Feb 12 '12 at 10:24
  • The duplicate contains the essential solution: Use `setInterval` to periodically run some code. – Rob W Feb 12 '12 at 10:25

5 Answers5

6

You can use setInterval to run your clk() function every second:

setInterval(clk, 1000); // run clk every 1000ms

MDN on setInterval

As nnnnnn points out, the timer interval probably won't be synchronized with the passage of an actual, real-time second, so using an interval like 100ms might not be a bad idea.

Twisol
  • 2,762
  • 1
  • 17
  • 17
  • 1
    Note: you _may_ find the clock runs more smoothly if you update more often than once per second, say every 100ms, because the timer interval isn't guaranteed to be exact. – nnnnnn Feb 12 '12 at 10:30
  • @nnnnnn: Great observation! I've incorporated that into my answer. :) – Twisol Feb 12 '12 at 10:35
0

A JavaScript digital clock from system time, can also manually set. :-)

 function timer(h,m,s){

 var sec; 
 var min; 
 var hrs; 
 var day;

 if(((s<=59) && (s>=0)) && ((m<=59) && (m>=0)) && ((h<=23) && (h>=0))){

 sec=s; 
 min=m; 
 hrs=h;

 //set parent element id 'lga' to your id 

 var parent = document.getElementById('lga'); 
 parent.innerHTML = '';
 var child = document.createElement('div'); 
 child.id = "thanesh";
 child.style = 'font-size:20px'; 
 parent.appendChild(child);

 setInterval(function(){ 

 sec++;

 if(sec==60){sec=0;min++;}
if(min==60){min=0;hrs++;}
if(hrs==24){hrs = 0; min = 0; sec = 0;}

if(hrs<=12){
day = 'AM';
}else{
day = 'PM';
}

document.getElementById('thanesh').innerHTML = '<table style="background-color:#f5f5f5;"><tr><td><div id="hh">0</div><td>'
                       +hrs+' : <td><div id="mm">0</div><td>'
                       +min+' : <td><div id="ss">0</div><td>'
                       +sec+' <td>'

                       +day+'</td></td></td></td></td></td></td></tr></table>';
if(sec>9){
document.getElementById('ss').style.display = "none";
}else if(sec==0){
document.getElementById('ss').style.display = "block";
}

if(min>9){
document.getElementById('mm').style.display = "none";
}else if(min==0){
document.getElementById('mm').style.display = "block";
}

if(hrs>9){
document.getElementById('hh').style.display = "none";
}else if(hrs==0){
document.getElementById('hh').style.display = "block";
}

},
1000);

}else{
alert("Check time inputs...!");
}
}

//Set Hour, Minutes, Seconds by JS / manually

var date = new Date();

var hst = date.getHours();
var mst = date.getMinutes();
var sst = date.getSeconds();

timer(hst,mst,sst);
  • Please explain it a little bit – Lithilion Nov 14 '18 at 06:57
  • clearly mention which part you can't understand ? I'm setting system time to the timer function and usual h:m:s calculation set between clock condition. this will increase the variable value with show hide element. –  Nov 21 '18 at 08:30
0

Since your "update every second" of the real clock competes with other computer tasks, the delay before the next real clock tic will be less than 1000 ms very often. So, better use setTimeout instead of setInterval. In fact, we just need to twist a little bit the end of the denied 姚先进's solution here arround, resulting in:

function clk() {
        var a=new Date();   
        document.getElementById("disp").innerHTML=a.getHours() + ":" + a.getMinutes() + ":" + a.getSeconds() ;
        setTimeout(clk, 1000 - a % 1000);
    }

This is my clock solution since 2007.

denis hebert
  • 128
  • 10
0

here we go

<html>

<head>
  <title>Javascript Clock</title>
  <script type="text/javascript">
    function clk() {
        setInterval(() => {
          var a = new Date();
          document.getElementById("disp").innerHTML = a.getHours() + ":" + a.getMinutes() + ":" + a.getSeconds();
        },1000);
      }
  </script>
</head>

<body>
  <input type="button" onclick="clk()" value="Display Clock" />
  <p id="disp">Clock Space</p>
</body>

</html>
  • It would be helpful for you to add some explanation of what this does and how it works, as well as what this approach can add to the set of answers already here – camille Dec 26 '21 at 23:13
0

You can add setTimeout(clk,1000); to your function,as bellow:

function clk() {
        var a=new Date();   
        document.getElementById("disp").innerHTML=a.getHours() + ":" + a.getMinutes() + ":" + a.getSeconds() ;
        setTimeout(clk,1000);
    }