Mój timer w javascript jest już prawie gotowy
const timer = document.querySelector('.timer');
const hours = document.querySelector('#timer-hours');
const minutes = document.querySelector('#timer-minutes');
const seconds = document.querySelector('#timer-seconds');
const alarm = new Audio ('timer.mp3');
function formatNumbers(e)
{
e.preventDefault();
const span = e.target;
if (e.code == 'Delete')
{
span.textContent == '00';
return;
}
if (/^\d$/.test(e.key))
{
const currentValue = span.textContent, inputValue = e.key;
let newValue = parseInt(currentValue + inputValue);
if (newValue > 99) newValue = newValue.toString().slice(-2);
if (newValue > 59) newValue = inputValue;
span.textContent = ('00' + newValue).slice(-2);
}
}
function countDown()
{
if (hours.textContent == 0 && minutes.textContent == 0 && seconds.textContent == 0)
{
alarm.play();
}
else
{
setTimeout('countDown()', 1000);
hours.setAttribute('contenteditable', 'false');
minutes.setAttribute('contenteditable', 'false');
seconds.setAttribute('contenteditable', 'false');
if (seconds.textContent>0)
{
seconds.textContent--;
if (seconds.textContent < 10)
{
seconds.textContent = '0' + seconds.textContent;
}
}
else
{
seconds.textContent = 59;
if (minutes.textContent>0)
{
minutes.textContent--;
if (minutes.textContent < 10)
{
minutes.textContent = '0' + minutes.textContent;
}
}
else
{
minutes.textContent = 59;
if (hours.textContent>0)
{
hours.textContent--;
if (hours.textContent < 10)
{
hours.textContent = '0' + hours.textContent;
}
}
}
}
}
}
timer.addEventListener('keydown', formatNumbers);
window.addEventListener('keydown', (event) => {
event.preventDefault();
if (event.key === 'Enter')
{
countDown();
}
})
Wszystko działa prawidłowo, prócz tego, że funkcję countDown można uruchomić nieograniczoną ilość razy, co obciąża procesor oraz przyspiesza timer. Jak naprawić ten błąd i uniemożliwić użytkownikowi wielokrotne wywołanie funkcji?
Codepen