如果你有本地存儲,你可以創建一個簡單持續 JS計時器:
// ensure u have localStorage (can be done better).
if (localStorage)
{
// get the localStorage variable.
let timerValue = localStorage.getItem('timerValue');
// if it's not set yet, set it.
if (!timerValue)
{
timerValue = new Date().toString();
localStorage.setItem('timerValue', timerValue);
}
// parse string date and get difference between now - old time in milliseconds.
let diff = new Date().getTime() - new Date(timerValue).getTime();
// compare difference and check if it matches 1 hour (1000ms * 60s * 60m)
if (diff >= 1000 * 60 * 60)
{
// reset timer immediately.
localStorage.setItem('timerValue', new Date().toString());
// do something..
}
}
希望它能幫助。
編輯:如果你希望計時器更新實時,你可以像提到,在使用的setInterval
編輯2:我有一個喜歡的,所以我提高了我的代碼位:
HTML:
<div id="timer"></div>
JS:
const AmountOfTimeToCheckInMs = 1000 * 60 * 60;
const PollingSpeedInMs = 1000;
class PersistentTimer
{
constructor()
{
// ensure u have localStorage (can be done better).
if (!localStorage)
{
console.log('localStorage not supported!');
return;
}
// get the timer element.
this.timerElement = document.querySelector('#timer');
// get the localStorage variable.
this.timerValue = localStorage.getItem('timerValue');
// if it's not set yet, set it.
if (!this.timerValue)
{
this.resetTimer();
}
this.updateTimer();
setInterval(() => this.triggerEverySecond(), PollingSpeedInMs);
}
triggerEverySecond()
{
this.updateTimer();
// compare difference and check if it matches 1 hour (1000ms * 60s * 60m)
if (this.getTimeDifference() >= AmountOfTimeToCheckInMs)
{
// reset timer immediately.
this.resetTimer();
// do something..
}
}
resetTimer()
{
this.timerValue = new Date().toString();
localStorage.setItem('timerValue', this.timerValue);
}
getTimeDifference()
{
// parse string date and get difference between now - old time in milliseconds.
return new Date().getTime() - new Date(this.timerValue).getTime();
}
updateTimer()
{
let calculatedDiffDate = new Date()
calculatedDiffDate.setTime(AmountOfTimeToCheckInMs - this.getTimeDifference());
this.timerElement.innerHTML = calculatedDiffDate.getMinutes() + 'm ' + calculatedDiffDate.getSeconds() + 's';
}
}
new PersistentTimer();
小提琴:https://jsfiddle.net/pwd46259/
來源
2017-10-06 13:48:22
Kai
你可以用'setTimeout'和運行,顯示'alert' – Tareq
不能肯定什麼問題,是一個功能? – guest271314
你可以使用'setInterval' – chakri