Skip to main content

Timer

Big O
tsc script.ts

Pure HTML​

let timerInterval: number | undefined;

const startButton = document.getElementById("start-btn") as HTMLButtonElement;
const stopButton = document.getElementById("stop-btn") as HTMLButtonElement;
const minutesInput = document.getElementById("minutes") as HTMLInputElement;
const timeLeftDisplay = document.getElementById("time-left") as HTMLElement;
const timerInputDiv = document.getElementById("timer-input") as HTMLElement;
const timerDisplayDiv = document.getElementById("timer-display") as HTMLElement;

startButton.addEventListener("click", function () {
const minutes = parseInt(minutesInput.value);

if (isNaN(minutes) || minutes <= 0) {
alert("Please enter a valid positive number of minutes.");
return;
}

if (timerInterval !== undefined) {
clearInterval(timerInterval); // Очищаем предыдущий таймер, если он существует
}

startTimer(minutes);
});

stopButton.addEventListener("click", function () {
clearInterval(timerInterval);
updateTimerDisplay(0); // Сбрасываем отображаемое время на 00:00
switchToInput();
});

function startTimer(minutes: number): void {
let timeLeft = minutes * 60;
switchToDisplay();

updateTimerDisplay(timeLeft);

timerInterval = setInterval(() => {
timeLeft--;

if (timeLeft <= 0) {
clearInterval(timerInterval);
switchToInput();
}

updateTimerDisplay(timeLeft);
}, 1000);
}

function updateTimerDisplay(timeLeft: number): void {
const minutes = Math.floor(timeLeft / 60);
const seconds = timeLeft % 60;
timeLeftDisplay.textContent = `${String(minutes).padStart(2, "0")}:${String(seconds).padStart(2, "0")}`;
}

function switchToDisplay(): void {
timerInputDiv.classList.add("hidden");
timerDisplayDiv.classList.remove("hidden");
}

function switchToInput(): void {
timerInputDiv.classList.remove("hidden");
timerDisplayDiv.classList.add("hidden");
minutesInput.value = ""; // Очищаем поле ввода
}