Skip to content

Instantly share code, notes, and snippets.

@iporsut
Created September 10, 2014 03:31
Show Gist options
  • Save iporsut/137cc405a8086305e351 to your computer and use it in GitHub Desktop.
Save iporsut/137cc405a8086305e351 to your computer and use it in GitHub Desktop.
JS Time Counter
<!doctype html>
<html>
<head>
<meta charset="utf-8"/>
</head>
<body>
<p>Minute : <span id="minute">0</span></p>
<p>Second : <span id="second">0</span></p>
<script type="text/javascript">
var second = 0;
var showMinute = document.querySelector("#minute");
var showSecond = document.querySelector("#second");
var lastCounterState = localStorage.getItem("lastCounterState");
if (lastCounterState != null) {
lastCounterState = JSON.parse(lastCounterState)
var currentTime = (new Date()).getTime()
var diffTime = Math.round((currentTime - lastCounterState.lastTime) / 1000.0);
second = lastCounterState.lastCounter + diffTime;
showMinute.innerHTML = Math.floor(second / 60);
showSecond.innerHTML = second % 60;
}
var counterInterval = setInterval(function() {
second++;
showMinute.innerHTML = Math.floor(second / 60);
showSecond.innerHTML = second % 60;
},1000);
window.onbeforeunload = function(event) {
clearInterval(counterInterval);
var currentState = {lastCounter : second, lastTime : (new Date()).getTime()};
localStorage.setItem("lastCounterState", JSON.stringify(currentState));
};
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment