make a live clock with existing time in div with javascript
javascript
Solution
It can be as easy as this:
setInterval(function(){
document.getElementById("updatetime").innerHTML = (new Date()).toLocaleTimeString();
}, 1000);
Or use the other Date methods to fine-tune your output.
Update
I only now realized that OP was asking not about incrementing an element with the current time but with a predetermined time.
That's less trivial, but here is a solution that should fit the original question:
function increment_time_element(element, delay) {
var interval, last,
time_pattern = /(\d+):(\d+):(\d+)/,
start = element.innerHTML.match(time_pattern),
then = new Date;
then.setHours (parseInt(start[1], 10) || 0);
then.setMinutes(parseInt(start[2], 10) || 0);
then.setSeconds(parseInt(start[3], 10) || 0);
function now() {
return Date.now ? Date.now() : (new Date).getTime();
}
last = now();
interval = setInterval(function () {
var current = now();
// correct for any interval drift by using actual difference
then.setTime(then.getTime() + current - last)
last = current;
element.innerHTML = then.toString().match(time_pattern)[0];
}, delay || 1000);
return {cancel: function() { clearInterval(interval) }};
}
// Usage:
var incrementing_time =
increment_time_element(document.getElementById("updatetime"));
// Then, if you want to cancel:
incrementing_time.cancel();
Problem
ok lets say we have a website that need a realtime time; example : `<div id="updatetime">21:12:52</div>` each seconds update hours:m:second. what i have in minds using the `interval function` to do long pool and add the sec +1 if to 60 then add + 1 to m and same as hours. but is there a function already solving this problem? how do you make this `21:12:52` a moving real clock with javascript that updates each seconds? i have search google, stackoverflow, many of them tells us how to make the current real time datetime from javascript. but none from an existing time. if there is please do insert the link.