每隔X分钟jQuery倒计时

时间:2015-06-27 14:24:28

标签: javascript jquery timer

社区,

我想知道如何创建一个每30分钟重启一次的计时器。

我刚创建了这个,但每次重新加载页面时都会重新启动:c

<script type="text/javascript">
    var ServerTime = new Date( );
    var iTimeStamp = 1412069179 -Math.round( +new Date() / 1000 );
    tTimer( iTimeStamp, "1412076600", "ctfTimer" );
    window.setInterval( 'tTimer(iTimeStamp,"1412076600","ctfTimer")', 250 );
</script>

function tTimer(iEndTimeStamp, iTimeStamp, sElement) {
iTimeStamp = iTimeStamp - Math.round(+new Date() / 1000) - iEndTimeStamp;
oElement = jQuery('#'+sElement);
if (iTimeStamp < 0) {
    oElement.html('00:00:00');
    return false;
}
diffDay = iTimeStamp / (3600 * 24 );
diffDay = diffDay.toString();
diffDay = diffDay.split(".");
diffHour = iTimeStamp / 3600 % 24;
diffHour = diffHour.toString();
diffHour = diffHour.split(".");
diffMin = iTimeStamp / 60 % 60;
diffMin = diffMin.toString();
diffMin = diffMin.split(".");
diffSek = iTimeStamp % 60;
diffSek = diffSek.toString();
diffSek = diffSek.split(".");
if(diffDay[0] != 0){
    oElement.html(diffDay[0] + 'd ' + checkLength(diffHour[0]) + ':' + checkLength(diffMin[0]) + ':' + checkLength(diffSek[0]));
    return true;
}
oElement.text(checkLength(diffHour[0]) + ':' + checkLength(diffMin[0]) + ':' + checkLength(diffSek[0]));
return true;}

function checkLength(sString) {
    sString = sString.toString();
    if (sString.length == 1) {
        sString = '0' + sString;
    }
    return sString;
}

我希望你对我有任何暗示或窍门。 此致

1 个答案:

答案 0 :(得分:2)

您可以使用localStorage轻松完成此操作。这是一个例子。

HTML:

<div>Time remaining: <span id="timer"></span></div>

JavaScript的:

var interval = 30000;

function reset() {
    localStorage.endTime = +new Date + interval;
}

if( ! localStorage.endTime ) {
    reset();
}

setInterval( function() {
    var remaining = localStorage.endTime - new Date;
    if( remaining >= 0 ) {
        $('#timer').text( Math.floor( remaining / 1000 ) );
    } else {
        reset();
    }
}, 100 );

Fiddle

在计时器启动后单击“运行”,或重新加载整个小提琴页面,以便从中断处继续查看计时器。

顺便说一句,当你使用setTimeout()setInterval()时,最好将它传递给一个实际的函数而不是一个包含函数源代码的字符串。这通常使用内联函数表达式完成,或者您可以使用命名函数。

由于您有重复的代码可以立即和定时器调用tTimer(),因此也可以删除重复。而不是:

tTimer( iTimeStamp, "1412076600", "ctfTimer" );
window.setInterval( 'tTimer(iTimeStamp,"1412076600","ctfTimer")', 250 );

你可以这样写:

function tick() {
    tTimer( iTimeStamp, '1412076600', 'ctfTimer' );
}

tick();
setInterval( tick, 250 );