繁体   English   中英

JavaScript脚本计时器问题

[英]Javascript script timer issue

我正在尝试倒计时。 我设法制作一个,但是问题是当我关闭浏览器时它停止了。 因此,当用户重新访问我的网站时,它将再次重新启动。 我要保留的计时器。 例如,如果用户在计时器22:14:09离开我的网站。 因此计时器将继续。 假设用户在一小时后重新访问了我的网站,因此时间应为21:14:09。 我怎样才能做到这一点?

这是我的JS

$(function () {
var hrs, mins, secs, TimerRunning, TimerID,
    Timer = {
        init: function () {
            hrs          = 23;
            mins         = 59;
            secs         = 59;
            TimerRunning = false;
            Timer.StopTimer();
            Timer.StartTimer();
         },

         StopTimer: function () {
            if(TimerRunning)
               clearTimeout(TimerID);
            TimerRunning=false;
         },

         StartTimer: function () {
            TimerRunning = true;
            $('.timer').html(Timer.Pad(hrs) + ":" + Timer.Pad(mins) + ":" + Timer.Pad(secs));
            TimerID = self.setInterval("StartTimer()", 1000);

            if(hrs == 0 && mins == 0 && secs == 0)
               StopTimer();

            if (secs == 0) {
               mins--;
               secs = 59;
            }
            if (mins == 0) {
                hrs--;
                mins = 59;
            }
            secs--;
            setTimeout(function () { Timer.StartTimer(); }, 1000);
         },

         Pad: function (number) {
            if(number < 10)
               number = 0+""+number;
            return number;
         }

    };

Timer.init();
});

更新资料

演示

这是我针对这个问题的解决方案。

// use hours, minutes & seconds to set time limit
var hours = 1, 
    minutes = 30, 
    seconds = 0,
    maxTime =  ( ( hours * 3600 ) + ( minutes * 60 ) + seconds ) * 1000,
    // if timeleft not in localStorage then default to maxTime
    timeLeft = ( localStorage.timeLeft || maxTime ),
    startTime = new Date(),
    intervalRef;

// check if user has already used up time
if( timeLeft > 0 ) {

    intervalRef = setInterval( setTimeLeft, 5000 );
} else {

    stopTrackingTime();
}

function setTimeLeft( ) {

    // if user has used up time exit
    if( localStorage.timeLeft < 0 ) {

        stopTrackingTime();
    }

    // calculate how long user has left
    var elapsed = ( new Date() - startTime );
    localStorage.timeLeft = timeLeft - elapsed;
};

// function called once user has used up time
function stopTrackingTime( ) {

    clearInterval( intervalRef );
    alert( "end of time allowed" );
}

在这里摆弄

您可以将时间存储在LocalStorage ,并且该时间将在浏览器重启后保持不变。

就您而言,简单到

localStorage["mytimer"] = JSON.stringify([hrs, mins, secs]);

应该可以存储,你可以做

var previousTime = JSON.parse(localStorage["mytimer"]);

检索先前的值。

您可以在这里阅读更多有关它的信息: http : //diveintohtml5.info/storage.html

您可以修改StartTimer函数,以便每次将其称为本地时间戳记( new Date )时都保存在cookie或localStorage中。 此外,setTimeout不是很可靠,您应该不时地实时调整时间计数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM