繁体   English   中英

javascript中的倒计时器使用setTimeout

[英]Countdown timer in javascript using setTimeout

我正在使用jquery创建一个倒数计时器,我在这里举了几个例子,并提出了以下代码。 问题是时间没有显示,我无法弄清楚出了什么问题。 被困了近2个小时..

回代码

    var day = 1;                        //countdown time
    var start = player.LastActive;      // Use UtcNow instead of Now
    var endTime = start.AddDays(day);   //endTime is a member, not a local variable
    Timespan remainingTime = endTime - DateTime.UtcNow;

我的javascript

var endTime = '<%= remainingTime%>';
var startTime = '<%= DateTime.UtcNow %>'

$(document).load(function () {
        countDown(endTime);
    });

    function countDown(endTime) {
        if (endTime > 0) {
            var d = document.getElementById("countDiv");
            d.innerHTML = endTime;
            setTimeout(function () { countDown(endTime - 1); }, 1000);
        }
    }

我的HTML

<div id="countDiv" style="float:left;margin-top: 13px; margin-left:5px;"></div>

我的目标是展示一个玩家每天移动多长时间:这是玩家最后一次活动后的第二天。 有人可以开导我..谢谢你

由于您的结束时间是您的javascript代码中的字符串,因此请先将其转换为整数

尝试这个

$(document).ready(function () {
        countDown(parseInt(endTime));
    });

使用$(window).load

要么

$(document).ready

但不是$(document).load

当你似乎使用jquery时,你可以做到

$(document).ready(function () {
        countDown(endTime);
    });

    function countDown(endTime) {
        if (endTime > 0) {
            $('#countDiv').text(secondsToTime(endTime));
            setTimeout(function () { countDown(endTime - 1); }, 1000);
        }
    }
function secondsToTime(secs)
{
    var hours = Math.floor(secs / (60 * 60));

    var divisor_for_minutes = secs % (60 * 60);
    var minutes = Math.floor(divisor_for_minutes / 60);

    var divisor_for_seconds = divisor_for_minutes % 60;
    var seconds = Math.ceil(divisor_for_seconds);

    return hours +':' + minutes + ':' + seconds;
}

几秒钟,它来自https://stackoverflow.com/a/6312999/961526 ,你可以采取另一个版本,你可以在那里找到。

jsFiddle

ready ,没有load

$(document).ready(function () {
  countDown(endTime);
});

或试试这个

  $(function() {
            countDown(endTime);
       });

 function countDown(parseInt(endTime)) {
        if (endTime > 0) {
            $('#countDiv').text(endTime);
            setTimeout(function () { countDown(endTime - 1); }, 1000);
        }
    }

暂无
暂无

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

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