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>
setTimeout
as suggested in a couple of answers is not the correct answer.setTimeout
andsetInterval
may look similar, butsetTimeout
is meant for single events, whilesetInterval
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.When you start the timer the
setTimeout
function returns the timer's ID, which you pass as argument for theclearTimeout
function: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 anXMLHttpRequest
. Just group the functions which don't need to be run 10 times per second, and execute them each time the tick counter resets.A JavaScript digital clock from system time, can also manually set. :-)
You can use
setInterval
to run your clk() function every second: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.
You can add
setTimeout(clk,1000);
to your function,as bellow: