4

When I load this in a browser it'll show the time it was when page was fully loaded, but won't update itself every second. How do I do this?

var h = date.getHours();   if(h<10) h = "0"+h;
var m = date.getMinutes(); if(m<10) m = "0"+m;
var s = date.getSeconds(); if(s<10) s = "0"+s;
document.write(h + " : " + m + " : " + s);
Darren
  • 68,902
  • 24
  • 138
  • 144
James Forbes
  • 199
  • 1
  • 2
  • 14

2 Answers2

7

Use setInterval:

setInterval(clock, 1000);

function clock() {
   var date = new Date();
   var h = date.getHours();   if(h<10) h = "0"+h;
   var m = date.getMinutes(); if(m<10) m = "0"+m;
   var s = date.getSeconds(); if(s<10) s = "0"+s;
   document.write(h + " : " + m + " : " + s);
}

Although you probably want to update a HTML element rather than document.write to the page every second.

http://jsfiddle.net/bQNwJ/

Darren
  • 68,902
  • 24
  • 138
  • 144
0

Wrap it up in a function and let it call itself:

everysecond=1000; // milliseconds
function showCurrentTime(){
    /*do your timing stuff here */
    if(someConditionIsntMet) setTimeout(showCurrentTime, everysecond)
}
Thomas Junk
  • 5,588
  • 2
  • 30
  • 43
  • very bad. set interval is better for this – Francisco Afonso May 04 '13 at 11:56
  • 2
    No. SetIntervall is not better. It is Ongoing. With the selfinvoking function, you have the possibility to abort at a given condition. there is no easy way to abort setInterval – Thomas Junk May 04 '13 at 11:56
  • @Lilith2k3 ...yes it is. What kind of logic makes you think this is better? – tckmn May 04 '13 at 11:57
  • @Doorknob: Like he said, it's more flexible. You can build setInterval easily from setTimeout, but not the other way around. – Janus Troelsen May 04 '13 at 11:58
  • @JanusTroelsen `var intr = setInterval(dostuff, 1000); clearInterval(intr)` – tckmn May 04 '13 at 11:59
  • In my eyes, setInterval is for this kind of jobs an AntiPattern. – Thomas Junk May 04 '13 at 11:59
  • `setInterval` is for repeating things! **Period.** That's what it does, that's what it was made to do. `setTimeout` is for delays, *that's the only thing it should be used for*. And about aborting it? `var intr = setInterval(dostuff, 1000); clearInterval(intr)`. – tckmn May 04 '13 at 12:00
  • 1
    `setInterval` is worse for this purpose because it is not dependent on the time it takes to run the function. You don't wanna update simultaneously if it takes a long time to run the function. See http://stackoverflow.com/a/731625/309483 PERIOOOOOOOOOOOOOD – Janus Troelsen May 04 '13 at 12:03