[英]How to Save and retrieve 24hrs Countdown timer to Local.Storage
我是一個 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>
要在本地存儲中保存某些內容,您可以使用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());
}
使用 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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.