我是一個JS新手。我有一個 24 小時倒數計時器,它會在頁面重新加載時重置,但是我想使用 LocalStorage 保存啟動進度,以便它在 24 小時后準確結束。這意味著即使頁面關閉,它也不會在啟動后立即停止或重新啟動。當頁面被訪問時,它總是會繼續倒計時。我的代碼如下
<div class="ml-2">Time Remaining <span id="remainingTime"></span></div>
<script>
// this code set time to 24 hrs
var timer2 = "36:00:00";
var session_timer = localStorage.getItem('timer2');
if(session_timer){
console.log('timer2',session_timer);
timer2 = session_timer;
}
var interval = setInterval(function() {
var timer = timer2.split(':');
//by parsing integer, I avoid all extra string processing
var hours = parseInt(timer[0], 10);
var minutes = parseInt(timer[1], 10);
var seconds = parseInt(timer[2], 10);
--seconds;
minutes = (seconds < 0) ? --minutes : minutes;
hours = (minutes < 0) ? --hours : hours;
if (hours < 0) clearInterval(interval);
minutes = (minutes < 0) ? 59 : minutes;
minutes = (minutes < 10) ? '0' minutes : minutes;
hours = (hours < 10) ? '0' hours : hours;
if (minutes < 0) clearInterval(interval);
seconds = (seconds < 0) ? 59 : seconds;
seconds = (seconds < 10) ? '0' seconds : seconds;
minutes = (minutes < 10) ? minutes : minutes;
timer2 = hours ':' minutes ':' seconds;
if(hours <= 0 && minutes == 0 && seconds == 0){
// if you want to delete it on local storage
// localStorage.removeItem('timer');
console.log('Transaction Cancelled')
}
else{
$('#remainingTime').html(timer2);
// if you want to save it on local storage
// localStorage.setItem('timer', timer2);
}
}, 1000);
</script>
uj5u.com熱心網友回復:
要在本地存盤中保存一些東西,你可以使用localStorage.setItem(key, value)
要從本地存盤中獲取一些東西,你可以使用localStorage.getItem(key, value)
if(hours <= 0 && minutes == 0 && seconds == 0){
// if you want to delete it on local storage
localStorage.removeItem('timer');
console.log('Transaction Cancelled')
}
else{
$('#remainingTime').html(timer2);
// if you want to save it on local storage
localStorage.setItem('timer', timer2.toString());
}
uj5u.com熱心網友回復:
使用 luxon js 并計算為 Millis 與處理小時、分鐘和秒
// this code set time to 24 hrs
let duration = luxon.Duration.fromObject({
days: 1
});
var interval;
function tick() {
let remaining = localStorage.getItem("interval") || duration.toMillis();
remaining -= 1000;
let d = luxon.Duration.fromMillis(remaining);
console.log(d.toHuman());
localStorage.setItem("interval", remaining);
}
function onLoad() {
var interval = setInterval(tick, 1000);
console.log("Timer Started");
}
function onUnLoad() {
cancelInterval(interval);
console.log("Timer Stopped");
}
onLoad();
onUnLoad();
<script src="https://moment.github.io/luxon/global/luxon.min.js"></script>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/446495.html
標籤:javascript jQuery
