1. 程式人生 > >js倒計時--天、時、分、秒, 到時間後自動停止

js倒計時--天、時、分、秒, 到時間後自動停止

js倒計時–天、時、分、秒, 到時間後自動停止:

在這裡插入圖片描述
在這裡插入圖片描述

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>積分清零公告</title>
    <script language="javascript" type="text/javascript">  
        var timer = null;
        function leftTimer(date) {
            clearTimeout(timer);
            var leftTime = new Date(date).getTime() - new Date().getTime(); //計算剩餘的毫秒數 
            if (leftTime <= 0) leftTime = 0;
            var days = parseInt(leftTime / 1000 / 60 / 60 / 24, 10); //計算剩餘的天數 
            var hours = parseInt(leftTime / 1000 / 60 / 60 % 24, 10); //計算剩餘的小時 
            var minutes = parseInt(leftTime / 1000 / 60 % 60, 10);//計算剩餘的分鐘 
            var seconds = parseInt(leftTime / 1000 % 60, 10);//計算剩餘的秒數 
            days = paddingZero(days);
            hours = paddingZero(hours);
            minutes = paddingZero(minutes);
            seconds = paddingZero(seconds);
            document.getElementById("timer").innerHTML = `${days}天 ${hours}:${minutes}:${seconds}`;

            if (leftTime >= 0) {
                timer = setTimeout(`leftTimer('${date}')`, 1000);
            }
        }
        function paddingZero(i) { //將0-9的數字前面加上0,例1變為01 
            return i < 10 ? "0" + i : i;
        }

    </script>
</head>

<body onload="leftTimer('2018/10/31 15:53:50')">
    <h2>剩餘時間:</h2>
    <div id="timer"></div>
</body>

</html>