簡體   English   中英

刷新頁面時內置的javascript計時器重置

[英]Timer built in javascript resets when page is refresh

我在將計時器存儲在localStorage中時遇到問題。 每次刷新瀏覽器時,計時器都會重置。 現在,我要做的就是將計時器存儲在localStorage中,以便每次用戶刷新瀏覽器時計時器都不會重置。 請在下面檢查我的代碼

HTML

<p class="w3-xlarge w3-serif"> <i>Linguistics Exam</i><span class="w3-right" id="timeLeft" name="timeLeft"></span></p>

JS

var total_seconds = 40*60;
var c_minutes = parseInt(total_seconds/60);
var c_seconds = parseInt(total_seconds%60);

function checkTime(){
    document.getElementById("timeLeft").innerHTML = 'Time Left: ' + c_minutes + ' : ' + c_seconds;

    if(total_seconds <= 0 ){
        $(document).ready(function(){$("#submitLinguistics").click();});

    }else{
        total_seconds = total_seconds - 1;
        c_minutes = parseInt(total_seconds/60);
        c_seconds = parseInt(total_seconds%60);
        setTimeout("checkTime()", 1000);
    }
}
setTimeout("checkTime()", 1000);

首先,將setTimeout更改為setInterval ,它將每秒鍾執行一次,而不是在每個實例上手動調用setTimeout

var total_seconds = 40*60;
var c_minutes = parseInt(total_seconds/60);
var c_seconds = parseInt(total_seconds%60);

function checkTime(){
document.getElementById("timeLeft").innerHTML = 'Time Left: ' + c_minutes + ' : ' + c_seconds;

if(total_seconds <= 0 ){
    $(document).ready(function(){$("#submitLinguistics").click();});
    clearInterval(myInterval);
}else{
    total_seconds = total_seconds - 1;
    c_minutes = parseInt(total_seconds/60);
    c_seconds = parseInt(total_seconds%60);
}
}
var myInterval = setInterval(checkTime, 1000);

接下來,您需要將total_seconds寫入localStorage

var total_seconds = localStorage.getItem("total_seconds") ? localStorage.getItem("total_seconds") : 40*60;
var c_minutes = parseInt(total_seconds/60);
var c_seconds = parseInt(total_seconds%60);

function checkTime(){
document.getElementById("timeLeft").innerHTML = 'Time Left: ' + c_minutes + ' : ' + c_seconds;

if(total_seconds <= 0 ){
    $(document).ready(function(){$("#submitLinguistics").click();});
    clearInterval(myInterval);
}else{
    total_seconds = total_seconds - 1;
    c_minutes = parseInt(total_seconds/60);
    c_seconds = parseInt(total_seconds%60);
}
localStorage.setItem("total_seconds", total_seconds);
}
var myInterval = setInterval(checkTime, 1000);

最后,如果您關閉標簽並在一段時間后重新打開它,則計數器將從原位重新加載,並且用戶可以通過關閉標簽,處理答案並再次打開來作弊。 為了應對這種情況,建議與服務器合作,即使用實際日期並根據該日期進行加載,而不是使用localStorage 程序員用戶甚至可以從開發工具的控制台中重置計時器。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM