倒计时,离开页面时停止,进入时恢复

倒计时,页面隐藏时停止倒计时,重新进入时恢复

html

<h2>剩余时间:</h2>
<h2 id="has-time"></h2>

js

// 倒计时
        let timer = null,
            t = 0,
            time = 0,
            timeout=false,
            getDate = new Date();
        function getCountDown(timestamp) {
            timer = setInterval(function () {
                var nowTime = new Date();
                var endTime = new Date(timestamp);

                t = endTime.getTime() - nowTime.getTime();
                var hour = Math.floor((t / 1000 / 60 / 60) % 24);
                var min = Math.floor((t / 1000 / 60) % 60);
                var sec = Math.floor((t / 1000) % 60);
                if (hour == 0 && min == 0 && sec == 0) {
                    // timeout = true;
                    // $(".submit-btn").click();
                    clearInterval(timer);
                }
                if (hour < 10) {
                    hour = "0" + hour;
                }
                if (min < 10) {
                    min = "0" + min;
                }
                if (sec < 10) {
                    sec = "0" + sec;
                }
                var countDownTime = hour + ":" + min + ":" + sec;
                $("#has-time").html(countDownTime);
            }, 1000);
        }

        //调用函数:
        getCountDown(new Date().getTime() + 1000 * 60 * 45);
    //监听是否离开页面
        document.addEventListener(
            "visibilitychange",
            function () {
                if (document.visibilityState == "hidden") {
                    clearInterval(timer);
                } else {
                    if (timeout) {
                        clearInterval(timer);
                    } else {
                        getCountDown(new Date().getTime() + t);
                    }
                }
            },
            false
        );

源代码:https://github.com/ouxiaojie18/-/blob/master/%E5%80%92%E8%AE%A1%E6%97%B6.html

posted @ 2018-09-28 17:13  mosquito~  阅读(945)  评论(0编辑  收藏  举报