JSFiddle - React, Tailwind, and code Playground
by Sergei Sokolov
HTML
<input type="button" id="start" value="Старт">
<input type="button" id="stop" value="Стоп">
<input type="button" id="clearText" value="Очистить">
<p class="timer"></p>
JavaScript
/**
* для вопроса https://qna.habr.com/q/798241
* Как отследить событие работающего таймера?
*/
const el_start = document.querySelector('#start');
const el_stop = document.querySelector('#stop');
const el_clearTextVar = document.querySelector('#clearText');
const el_timer = document.querySelector('.timer');
let timer = null;
let value = 0;
const display = () => el_timer.innerText = value;
function timerStart(){
if (timer) return;
timer = setInterval(() => {
value++;
display();
}, 1000);
};
function timerStop(){
clearInterval(timer);
timer = null;
};
function clearText() {
if (timer) timerStop();
value = 0;
display();
}
el_start.addEventListener('click', timerStart);
el_stop.addEventListener('click', timerStop);
el_clearTextVar.addEventListener('click', clearText);
display();