I have a website that retrieves time data from any given location on the world live.
I wanted to be able to automatically change the time and not deal with the hassle of local client times.
It's fairly simple, but since I'm not that good with JS, I'd like to know if there is anything I could improve about it?
Suggestions are welcome!
(function() {
"use strict";
var LiveTime = {
rawOffset: null,
dstOffset: null,
timeoutId: null,
setOffset: function(raw, dst) {
LiveTime.rawOffset = raw * 1000;
if (typeof dst !== "undefined") {
LiveTime.dstOffset = dst * 1000;
}
},
start: function() {
LiveTime.timeoutId = (function increment() {
var now = new Date();
var now = new Date(
now.getUTCFullYear(),
now.getUTCMonth(),
now.getUTCDate(),
now.getUTCHours(),
now.getUTCMinutes(),
now.getUTCSeconds(),
now.getUTCMilliseconds()
);
now.setTime(now.valueOf() + LiveTime.rawOffset + LiveTime.dstOffset);
var element = document.getElementById("current-time");
element.innerHTML = ("0" + now.getHours()).slice(-2) + ":"
+ ("0" + now.getMinutes()).slice(-2) + ":"
+ ("0" + now.getSeconds()).slice(-2);
LiveTime.timeoutId = setTimeout(increment, 50);
})();
},
stop: function() {
clearTimeout(LiveTime.timeoutId);
}
}
//usage example
LiveTime.start();
//simulate new location after 5 seconds
setTimeout(function() {
LiveTime.setOffset(-9 * 3600, 3600); //alaska
}, 5000);
//stop the time after 5 more seconds
setTimeout(function() {
LiveTime.stop();
}, 10000);
})();
<div id="current-time"></div>