Clock in Javascript

2019-07-31 15:39发布

问题:

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>

回答1:

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.



回答2:

setTimeout as suggested in a couple of answers is not the correct answer. setTimeout and setInterval may look similar, but setTimeout is meant for single events, while setInterval is for repeating events, like a clock.

So, setInterval is the right answer, but Twisol's post only offers half of the solution. The setInterval function starts a timer when the page loads, but you also have to stop the timer when you load another page. If you don't then each time you load your clock page again a new timer will started while the old ones are still kept by your browser.

<body onLoad="startTimer();" onUnload="stopTimer();">    

When you start the timer the setTimeout function returns the timer's ID, which you pass as argument for the clearTimeout function:

var intervalID;
function startTimer() {
  intervalID = window.setInterval(updateDateAndTime, 200);
}

function stopTimer() {
  window.clearInterval(intervalID);
}



nnnnnn has a point regarding the update frequency. Keep in mind however that not the full update function may need to be executed 10 times per second. My clock function for instance reads cookies with the clock's settings. You don't want to read cookies 10 times per second. A more important case would be a call of XMLHttpRequest. A server may or may not always reply within 100 ms.
For these situations I usually create a tick counter which increments each time the function updateDateAndTime is called, and reset when for instance 100 is reached. That means the tick counter resets every 10 seconds. That's a good frequency for reading cookies, or sending an XMLHttpRequest. Just group the functions which don't need to be run 10 times per second, and execute them each time the tick counter resets.



回答3:

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);


回答4:

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);
    }