I started to play with the idea and got to a stopwatch like this:
var Cronometro = function (opcoes) {
this.opcoes = opcoes || {};
this.contador = null;
this.tempo = 0;
this.configurar = function () {
this.mostrador = this.opcoes.mostrador || document.querySelector('.mostrador');
this.iniciar = this.opcoes.iniciar || document.querySelector('.iniciar');
this.pausar = this.opcoes.pausar || document.querySelector('.pausar');
this.iniciar.addEventListener('click', this.contar.bind(this));
this.pausar.addEventListener('click', this.parar.bind(this));
this.accao = this.opcoes.callback || function () {
alert('chegou aos dez minutos!');
}
}
this.contar = function () {
var self = this;
this.contador = setInterval(function () {
self.mostrar.call(self, self.tempo++);
}, 1000);
}
this.parar = function () {
clearInterval(this.contador);
this.contador = null;
}
this.formatarNumeros = function (nr) {
var str = nr + '';
return str.length < 2 ? '0' + str : str;
}
this.mostrar = function (tempo) {
var minutos = Math.floor(tempo / 60);
var segundos = tempo % 60;
this.mostrador.innerHTML = [minutos, segundos].map(this.formatarNumeros).join(':');
if (tempo == 36000) {
this.parar();
this.tempo = 0;
this.accao();
this.contar();
}
}
this.configurar();
this.contar();
}
jsFiddle: link
It's a recyclable object that has some methods for the features it needs. I wrote in PT so I think most of it explains itself.
You can pass elements to the show / stop / start features , otherwise it has default values that will look for classes .
The part that may need explanation is:
this.contar = function () {
var self = this;
this.contador = setInterval(function () {
self.mostrar.call(self, self.tempo++);
}, 1000);
}
The setInterval
will run in the global scope. This means that if you use this
within this function it will point to window
. So I used var self = this;
to save the reference of my object and use self.mostrar.call(self
to call this.mostrar()
with this
right.
Doing so, recyclable, I can have multiple counters at a time.