带输入域的倒数计时器

时间:2016-05-05 07:42:16

标签: jquery html refresh countdown jquery-countdown

我确定有人已经明白这一点,但我似乎无法在我的身上找到它。

我所拥有的是一个非常基本的倒计时,用户将分钟数量输入输入字段,点击按钮,然后倒计时分钟。

我想知道的是只是倒计时 忽略页面刷新时(继续按原样继续)。目前,它只是停止倒计时。

这是我到目前为止所拥有的。

HTML:

<form>
<input id="tminus" placeholder="0:00"></input>
<input id="request" placeholder="Enter Minutes here"></input>
<a href="#" class="button enterTime">Submit Time</a>
 <input type="reset" value="Clear form" />
</form>

JS:

$('.enterTime').click(function () {
    var reqVal = $('#request').val();
    var parAmt = parseInt(reqVal);
    var totalAmount = parAmt * 60;
     $('#request').val(" ");

    var timeloop, timeSet = function () {

        totalAmount--;

        var minutes = parseInt(totalAmount/60);
        var seconds = parseInt(totalAmount%60);

        if(seconds < 10)
            seconds = "0"+seconds;
        $('#tminus').val(minutes + ":" + seconds);
    };

    var timeloop  = setInterval(timeSet, 1000);

})

感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

您可以将totalAmount保存到localStorage,并在用户刷新页面时从中获取值。围绕你需要的东西:

Fiddle

// Get totalAmount from localStorage and if there is positive value call timeSet() immediately
var totalAmount = localStorage.getItem('countDown') || 0,
    timeloop;

if (totalAmount) {
    timeSet()
}

function timeSet () {
    totalAmount--;
    // Refresh value in localStorage
    localStorage.setItem('countDown', totalAmount);

     // If countdown is over, then remove value from storage and clear timeout
     if (totalAmount < 0 ) {
         localStorage.removeItem('countDown');
         totalAmount = 0;
         clearTimeout(timeloop);
         return;
     }

    var minutes = parseInt(totalAmount/60);
    var seconds = parseInt(totalAmount%60);

    if(seconds < 10)
        seconds = "0"+seconds;

    $('#tminus').val(minutes + ":" + seconds);

    timeloop = setTimeout(timeSet, 1000);
}

$('.enterTime').click(function () {
    var reqVal = $('#request').val();
    var parAmt = parseInt(reqVal);

    if (timeloop) {
        clearTimeout(timeloop)
    }

    totalAmount = parAmt * 60;

    $('#request').val(" ");

    timeSet();
})

// Clear timeout and remove localStorage value when resetting form
$('#countdown').on('reset', function () {
    totalAmount = 0;
    clearTimeout(timeloop);
    localStorage.removeItem('countDown');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="countdown">
    <input id="tminus" placeholder="0:00" />
    <input id="request" placeholder="Enter Minutes here" />
    <a href="#" class="button enterTime">Submit Time</a>
    <input type="reset" value="Clear form" />
</form>