I'm asking this because I haven't seen another solution in a similar layout to how I've done it.
Essentially I'm building a simple countdown timer for a portfolio piece and I'm trying to add a pause function to the timer. However, I can't figure out how to write it with Intervals and save the time remaining to a global variable to then re-access it when the continue button is clicked.
Any help would be greatly appreciated!
const timerDisplay = document.querySelector(".displayTimer");
const titleDisplay = document.querySelector(".titleDisplay");
const endTime = document.querySelector(".timeLeft");
let countdown;
let timerSettings = {
study: 25,
short: 5,
long: 45,
intervals: 4,
pause: timer.countdown,
};
/////////// BUTTONS ////////////////
const startBtn = document.getElementById("startBtn");
const pauseBtn = document.getElementById("pauseBtn");
///////// FUNCTIONALITY /////////////
function timer(seconds) {
clearInterval(countdown);
const now = Date.now();
const then = now + seconds * 1000;
displayTimeLeft(seconds);
displayEndTime(then);
countdown = setInterval(() => {
const secondsLeft = Math.round((then - Date.now()) / 1000);
if (secondsLeft < 0) {
clearInterval(countdown);
return;
}
displayTimeLeft(secondsLeft);
}, 1000);
}
function displayTimeLeft(seconds) {
const minutes = Math.floor(seconds / 60);
const remainderSeconds = seconds % 60;
/////////////////////////////////////
const display = `${minutes}:${
remainderSeconds < 10 ? "0" : ""
}${remainderSeconds}`;
timerDisplay.textContent = display;
///////////////////////////////////////
const titleDisplayer = `${minutes}:${
remainderSeconds < 10 ? "0" : ""
}${remainderSeconds} - Pomodoro Timer`;
titleDisplay.textContent = titleDisplayer;
}
function displayEndTime(timestamp) {
const end = new Date(timestamp);
const hour = end.getHours();
const minutes = end.getMinutes();
endTime.textContent = `Focus until ${hour < 10 ? "0" : ""}${hour}:${
minutes < 10 ? "0" : ""
}${minutes}`;
}
function pause() {
clearInterval(countdown);
interval = null;
}
/////////////////////
/// Button Events ///
/////////////////////
startBtn.addEventListener("click", function () {
timer(timerSettings.study * 60);
startBtn.textContent = `Pause`;
startBtn.style.display = "None";
pauseBtn.style.display = "inline";
});
pauseBtn.addEventListener("click", function () {
// timer(timerSettings.study * 60);
startBtn.textContent = `Start`;
startBtn.style.display = "Inline";
pauseBtn.style.display = "None";
});
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…