首页 > 代码库 > javascript 简单时间倒计时。

javascript 简单时间倒计时。

给一个新人讲解时随手写的demo~

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8" />
    <title>倒计时</title>
    <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
    <script>
        function getTimeStr(time)
        {
            var d=Math.floor(time/86400);
            time=time-d*86400;
            var h=Math.floor(time/3600);
            time=time-h*3600;
            var m=Math.floor(time/60);
            time=time-m*60;
            var s=time
            if (h<10) h="0"+h;
            if (m<10) m="0"+m;
            if (s<10) s="0"+s;
            return d+""+h+":"+m+":"+s
        }
        var leftTime=0;
        var timer=null;
        function timeStep()
        {
            leftTime=leftTime-1;
            $("#leftTime").html(getTimeStr(leftTime));
            if (leftTime==0)
            {
                alert("时间到拉。")
                clearTimeout(timer)
                timer=null;
            }
            else
            {
                timer=setTimeout(timeStep,1000);
            }
        }
        $(function(){
            $(document).on("click","#beginBtn",function(){
                var beginTime=$("#time").val();
                if (beginTime==""){
                    beginTime=0;
                }
                leftTime=beginTime;
                $("#leftTime").html(getTimeStr(leftTime));

                if (timer||beginTime==0) return
                timer=setTimeout(timeStep,1000)
            });
        });
    </script>
</head>
<body>    
    <span id="leftTime" style="min-height: 50px;line-height:50px;display:block;">00:00:00</span>
    <input type="number" id="time" / >
    <button id="beginBtn">开始倒计时</button>
</body>
</html>

 

javascript 简单时间倒计时。