Skip to main content
 首页 » 编程设计

c#之使用setTimeout在javascript中倒数计时器

2024年02月13日37hnrainll

我正在使用 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> 

我的目标是展示多长时间,让玩家获得他的日常 Action :这是玩家上次事件时间之后的一天。有人可以启发我..谢谢

请您参考如下方法:

使用$(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