Your idea is on the right track. You have to put the counterms
in a common scope for you to use clearInterval(counterms)
.
I also suggest you withdraw var id_label_ms = document.getElementById("count_label_ms");
out of the setInverval
not to weigh in performance. This element needs only once, not every 10 milliseconds.
I have put together other ideas, some suggested in the comments here.
window.onload = function () {
var countms = 0;
var counterms;
var id_label_ms = document.getElementById("count_label_ms");
var cronometro = {};
var ativo = false;
cronometro.start = function () {
if (ativo) return;
ativo = true;
counterms = setInterval(function () {
countms = countms + 1;
id_label_ms.innerHTML = countms / 100 + " s";
}, 10);
};
cronometro.stop = function () {
clearInterval(counterms);
ativo = false;
};
cronometro.reset = function () {
cronometro.stop();
ativo = false;
id_label_ms.innerHTML = countms = 0;
};
['start', 'stop', 'reset'].forEach(function (tipo) {
var input = document.querySelector('input[name="' + tipo + '"]');
input.addEventListener('click', cronometro[tipo]);
});
};
Thanks @Rgio and how can I restart from 0 (reset) ?
– akm
@akm I joined now.
– Sergio
it would not be better to put the
var id_label_ms = document.getElementById("count_label_ms");
out of methods, so you don’t have to look for him?– Tobias Mesquita
@Tobymosque yes, it would be better. I wanted to give an example with addeventlistener with closed scope but I had to leave and put later.
– Sergio
@Sergio would also be interesting to lock the start button when the timer is running so as not to bug the team
– MarceloBoni
@Marcelobonifazio good idea, joined in my new version.
– Sergio
@Tobymosque I have now joined a version that pleases me more :)
– Sergio
Who gave the
-1
can comment. I always thank anyone who points out mistakes and like to discuss different ideas.– Sergio
@Sergio, your method is not working continuously. the buttons seem to change behavior. After a few clicks it just stopped working and became infinite.
– Ivan Ferrer
@Sergio, if you click start, then reset, and click start it stops working.
– Ivan Ferrer
@Ivanferrer thanks, had a bug from the previous version. The
stop();
should becronometro.stop();
. Corrected.– Sergio
got better now.
– Ivan Ferrer