How to make time function update itself?

function, javascript, setinterval, time

Solution

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/

Problem

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

Original source

Related problems