Skip to content

Instantly share code, notes, and snippets.

@noclat
Created February 4, 2016 09:44
Show Gist options
  • Save noclat/41dd1d6f6911bb22cbd0 to your computer and use it in GitHub Desktop.
Save noclat/41dd1d6f6911bb22cbd0 to your computer and use it in GitHub Desktop.
/*
Small timer script by Nicolas Torres
(WIP: needs settings & a some few more helpers)
Usage:
<span id="chrono"></span> // set an element
chrono.start() // starts the timer
chrono.toggle() // play or pause the timer
chrono.stop() // stop and reset the timer
*/
window.chrono = (function() {
this.element = document.getElementById('chrono');
this.ref = false;
this.wait = localStorage['wait']?parseInt(localStorage['wait']):0;
this.diff = 0;
this.pause = false;
this.write = function(content) {
if (!content) content = '0:00';
if (this.element) this.element.innerHTML = content;
else console.log('Chrono: '+content);
};
this.update = function() {
if (this.ref == 0) return;
if (this.pause !== false) localStorage['wait'] = this.wait = ((new Date()).getTime() - this.pause);
else {
this.diff = ((new Date()).getTime() - this.ref - this.wait)/1000;
this.write(Math.floor(this.diff/60)+':'+("0"+Math.floor(this.diff%60)).slice(-2));
}
requestAnimationFrame(this.update);
};
this.toggle = function() {
if (this.ref == 0) this.start();
else this.pause = (this.pause === false)?(new Date()).getTime()-this.wait:false;
};
this.start = function() {
if (this.ref > 0) return;
localStorage['ref'] = this.ref = localStorage['ref']?parseInt(localStorage['ref']):(new Date()).getTime();
this.update();
};
this.stop = function() {
this.ref = 0;
this.wait = 0;
localStorage.clear();
this.write();
};
this.write();
if (localStorage['ref']) this.start();
return this;
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment