Skip to content

Instantly share code, notes, and snippets.

@PifyZ
Last active August 29, 2015 14:09
Show Gist options
  • Save PifyZ/fef4a2386787c5320b83 to your computer and use it in GitHub Desktop.
Save PifyZ/fef4a2386787c5320b83 to your computer and use it in GitHub Desktop.
Chronomètre
/*
id : String - l'identifiant d'un élément HTML (un div ou un span par exemple)
seconds : Int - Nombre de secondes
*/
function Stopwatch(id, seconds) {
var self = this;
this.seconds = seconds;
this.el = document.getElementById(id);
this.h = this.m = this.s = 0;
this.timer = setInterval(function() {
self.tick();
}, 1000);
this.tick();
};
Stopwatch.prototype.tick = function() {
if (this.seconds < 0) {
clearInterval(this.timer);
} else {
this.h = Math.floor(this.seconds / 3600);
this.m = Math.floor((this.seconds - (this.h * 3600)) / 60);
this.s = Math.floor(this.seconds % 60);
this.show();
this.seconds--;
}
};
Stopwatch.prototype.show = function() {
var hh = this.h < 10 ? '0' + this.h : this.h;
var mm = this.m < 10 ? '0' + this.m : this.m;
var ss = this.s < 10 ? '0' + this.s : this.s;
this.el.innerHTML = hh + ':' + mm + ':' + ss;
};
// Utilisation :
new Stopwatch('stats', 2);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment