如何解决向 setInterval 计时器添加“暂停”功能
我之所以这么问是因为我还没有看到过与我的做法类似的其他解决方案。
本质上,我正在为作品集构建一个简单的倒数计时器,并且我正在尝试向计时器添加暂停功能。但是,我不知道如何使用 Intervals 编写它并将剩余时间保存到全局变量中,然后在单击继续按钮时重新访问它。
任何帮助将不胜感激!
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";
});
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。