I played with the idea and came to a time 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();
}
It is a recyclable object that has some methods for the functionalities it needs. I wrote in PT so I think most of them explain themselves.
You can pass elements to the show/stop/start features, if it does not have default values it will look for classes.
The party that may need an 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. That means using this
within this function it will point to the window
. So I used var self = this;
to store the reference of my object and use self.mostrar.call(self
to call this.mostrar()
with the this
right.
Doing so, recyclable, I can have multiple counters at the same time.
Well, you like to play with what you design, I’m like that too! , It worked in perfect harmony, I really liked it because the way Oce set up the function made it malleable and easy to manipulate, It was great, I made great adaptations, Thank you so much for adding my knowledge and helping me =D
– Elaine
@Elaine I’m glad I could help!
– Sergio