Your idea is on the right path. You must put counterms
in a common scope so you can use clearInterval(counterms)
.
I also suggest you remove var id_label_ms = document.getElementById("count_label_ms");
out of setInverval
so as not to weigh performance. This element needs only once, not every 10 milliseconds.
I've 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]);
});
};
jsFiddle: link