Last active
August 29, 2015 14:09
-
-
Save PifyZ/fef4a2386787c5320b83 to your computer and use it in GitHub Desktop.
Chronomètre
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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