Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make time function update itself?

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);
like image 686
James Forbes Avatar asked Mar 24 '23 02:03

James Forbes


1 Answers

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/

like image 166
Darren Avatar answered Mar 29 '23 23:03

Darren