JS-实现秒表倒计时+缓存倒计时

实现秒表倒计时+缓存倒计时功能

<!DOCTYPE html>
<html>

    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>

    <body>
        <p class="diffDate"></p>
        <p class="counterSecond"></p>
    </body>
    <script type="text/javascript">
        countTime();
        function countTime() {
            var date = new Date();
            var now = date.getTime();

            var date2 = new Date();
            //倒计时10天
            date2.setDate(date2.getDate() + 10);

            var d, h, m, s, ms;
            //从本地获取保存的时间
            var leftTime = '';
            var cacheDate = localStorage.getItem( "counter");
            if(cacheDate) {
                //缓存有值
                leftTime = new Date(parseInt(cacheDate)).getTime() - 1000;
                //更新缓存
                localStorage.setItem("counter", leftTime);
            }
            //如果没有缓存或时间过期
            if(!cacheDate || leftTime < 0) {
                leftTime = date2.getTime() - now;
                //保存最后时间
                localStorage.setItem("counter", leftTime - 1000);
            }

            if(leftTime >= 0) {
                d = Math.floor(leftTime / 1000 / 60 / 60 / 24 % 31);
                h = Math.floor(leftTime / 1000 / 60 / 60 % 24);
                m = Math.floor(leftTime / 1000 / 60 % 60);
                s = Math.floor(leftTime / 1000 % 60);
                ms = Math.floor(leftTime % 1000);
                if(d < 10) {
                    d = "0" + d;
                }
                if(h < 10) {
                    h = "0" + h;
                }
                if(m < 10) {
                    m = "0" + m;
                }
                if(s < 10) {
                    s = "0" + s;
                }
            }
            //console.log(d + ":" + h + ":" + m + ":" + s + ":" + ms)
            document.getElementsByClassName("diffDate")[0].innerHTML = d + ":" + h + ":" + m + ":" + s;
        }
        setInterval(countTime, 1000);

        var diffCount = 0;
        /**
         * 从0到100计数
         */
        function countMilSecond() {
            ++diffCount;
            if(diffCount >= 100) {
                diffCount = 0;
            }
            if(diffCount < 10) {
                diffCount = '0' + diffCount;
            }
            document.getElementsByClassName("counterSecond")[0].innerHTML = diffCount;
        }
        setInterval(countMilSecond, 10);
    </script>

</html>

效果:
这里写图片描述

猜你喜欢

转载自blog.csdn.net/wang704987562/article/details/81588822