我下載了一個網站模板,一切似乎都在作業。我唯一的問題是我的計時器總是在重新加載頁面時再次啟動。我能做些什么來防止它?我看到了一些關于節省存盤時間的內容,但我的編碼知識非常少。提前感謝您的幫助。
(我不想更改布局和 css,所以我只上傳了 main.js 計時器部分和我的 html 檔案中的特定位置。我的問題仍然有太多代碼,所以我需要添加更多細節。我只是在寫一些額外的東西請忽略)。
const countDownClock = (number = 100, format = 'seconds') => {
const d = document;
const daysElement = d.querySelector('.days');
const hoursElement = d.querySelector('.hours');
const minutesElement = d.querySelector('.minutes');
const secondsElement = d.querySelector('.seconds');
let countdown;
convertFormat(format);
function convertFormat(format) {
switch (format) {
case 'seconds':
return timer(number);
case 'minutes':
return timer(number * 60);
case 'hours':
return timer(number * 60 * 60);
case 'days':
return timer(number * 60 * 60 * 24);
}
}
function timer(seconds) {
const now = Date.now(`November 17 00:00:00`);
const then = now seconds * 1000;
countdown = setInterval(() => {
const secondsLeft = Math.round((then - Date.now()) / 1000);
if (secondsLeft <= 0) {
setInterval(countdown);
return;
};
displayTimeLeft(secondsLeft);
}, 1000);
}
function displayTimeLeft(seconds) {
daysElement.textContent = Math.floor(seconds / 86400);
hoursElement.textContent = Math.floor((seconds % 86400) / 3600);
minutesElement.textContent = Math.floor((seconds % 86400) % 3600 / 60);
secondsElement.textContent = seconds % 60 < 10 ? `0${seconds % 60}` : seconds % 60;
}
}
/*
start countdown
enter number and format
days, hours, minutes or seconds
*/
countDownClock(15, 'days');
<div id="countdown" class="countdown">
<ul id="countdown-example">
<li>
<span class="days"></span>
<p class="days_text">DAYS</p>
</li>
<li>
<span class="hours"></span>
<p class="hours_text">HOURS</p>
</li>
<li>
<span class="minutes"></span>
<p class="minutes_text">MINS</p>
</li>
<li>
<span class="seconds"></span>
<p class="seconds_text">SECS</p>
</li>
</ul>
</div>
uj5u.com熱心網友回復:
歡迎使用 stackoverflow SXNSITVTY。
要實作您想要的,您需要將當前值存盤到localstorage。
然后,您可以在代碼中使用存盤的值。我認為,在查看您的代碼時,實作應該在這里
const now = Date.now(`November 17 00:00:00`);
const then = now seconds * 1000;
countdown = setInterval(() => {
let secondsLeft = Math.round((then - Date.now()) / 1000);
const storedSecondsLeft = localStorage.getItem('secondsLeft');
// check if you have localstorage stored
// then override the value of secondsLeft with the localstorage
if (storedSecondsLeft) {
secondsLeft = storedSecondsLeft
}
if (secondsLeft <= 0) {
clearInterval(countdown);
return;
};
// implement localstorage here
localStorage.setItem('secondsLeft', secondsLeft)
displayTimeLeft(secondsLeft);
}, 1000);
}
希望你理解這個想法
uj5u.com熱心網友回復:
在加載網頁時,如評論已經指出的那樣,從本地存盤中檢索倒數計時器,并將其作為您的起始值。確保檢查是否實際設定了本地存盤,并設定初始值以防他們第一次訪問的不是 IE。
確保您的 setInterval 函式在每次執行該函式時使用新計時器更新本地存盤。您可以將其存盤為時間戳。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/358971.html
標籤:javascript html 倒计时器
上一篇:如何更改tkinterttk.PanedWindow小部件的背景顏色?
下一篇:用遞回提取嵌套陣列的最后一個元素
