setInterval 时间在每个循环后变得更快

setInterval time becomes faster after every cycle

您好,我正在尝试跟踪用户在网页上花费的时间。所以我写了下面的 javascript 来做到这一点。

脚本开始跟踪 window 成为焦点的时间,然后在用户移动到其他选项卡或最小化 window 时暂停。

here is the fiddle:

代码如下:

$(function(){
    var count = 0;
    var interval;

    var ispaused=false;
    function setPause(){
        ispaused=true;
    }

    function unpause(){
        ispaused=false;
    }

    $(window).on("blur focus", function(e) {
        var prevType = $(this).data("prevType");

        if (prevType != e.type) {   //  reduce double fire issues
            switch (e.type) {
                case "blur":
                    setPause();
                    clearInterval(interval);
                    break;
                case "focus":
                    unpause();
                    var interval = setInterval(
                        function(){
                            if(!ispaused) {
                                $('#timer').text(count += 1);
                            }
                        },1000
                    );
                    break;
            }
        }

        $(this).data("prevType", e.type);
});

});

计时器在您聚焦区域时启动,并在模糊时暂停,但每次聚焦和模糊循环后计时器会变得更快。不知道为什么会这样。请帮忙!

我检查了你提供的 fiddle 并发现你将间隔变量存储在局部变量上我试图解决问题以查看它是否有效并更新了 fiddle 这里:

http://jsfiddle.net/9fzd1dap/1/

这是更新后的脚本

    $(function () {
        var count = 0;
        var interval; //This is the global interval variable

        var ispaused = false;
        function setPause() {
            ispaused = true;
        }

        function unpause() {
            ispaused = false;
        }

        $(window).on("blur focus", function (e) {
            var prevType = $(this).data("prevType");

            if (prevType != e.type) {   //  reduce double fire issues
                switch (e.type) {
                    case "blur":
                        setPause();
                        break;
                    case "focus":
                        unpause();
                        clearInterval(interval);
                        //I removed the var keyword from the line below to prevent dual declarations.
                        interval = setInterval(
                            function () {
                                if (!ispaused) {
                                    $('#timer').text(count += 1);
                                }
                            }, 1000
                        );
                        break;
                }
            }

            $(this).data("prevType", e.type);
        });

    });

发生的事情是全局区间变量没有被填充,局部区间(函数内部)变量是一个人口稠密。我已经在更新后的 fiddle 上对其进行了测试并且似乎工作正常 ;)