开发者

JS: setInterval and blur

开发者 https://www.devze.com 2023-01-22 06:07 出处:网络
I have this: $(window).blur(function() { setInterval(function() { $.ajax({ type: \"POST\", url: \"imback.php\",

I have this:

$(window).blur(function() {
    setInterval(function() {
        $.ajax({
            type: "POST",
            url: "imback.php",
            data: {
                mode: 'ajax',
                getUpdates: 'auto',
            },
            success: function(msg){
                document.title = msg + titleOrig;
            }
        });
    }, 35000);

Works fine.

A开发者_如何转开发lthough, if you have been blur, and then when you focus back, it will keep making the ajax call, it doesnt stop sending ajax call after interval 35 seconds.

How can i fix this? })


You need to store the interval when you set it, and then clear it on window focus. Like this:

(function() {
    var interval = null;

    $(window).blur(function() {
        if (interval) clearInterval(interval);
        interval = setInterval(function() {
            $.ajax({
                type: "POST",
                url: "imback.php",
                data: {
                    mode: 'ajax',
                    getUpdates: 'auto',
                },
                success: function(msg){
                    document.title = msg + titleOrig;
                }
            });
        }, 35000);
    });

    $(window).focus(function() {
        if (interval) clearInterval(interval);
        interval = null;
    });
})();

EDIT: I added (function() { ... })() around the code to encapsulate the "interval" variable, essentially making it "private" to the window blur and focus handlers.


Looks like you need to clearInterval() on focus


Using a closure:

$(window).blur(function() {
    tracktime = new Date();
    var iVal = setInterval(function() {
        $.ajax({
            type: "POST",
            url: "imback.php",
            data: {
                mode: 'ajax',
                getUpdates: 'auto',
            },
            success: function(msg){
                document.title = msg + titleOrig;
            }
        });
    }, 2000);

    $(window).focus(function() { clearInterval(iVal); });
});

This allows you to not have to check if you've set the Interval before clearing it. And, it lets you ensure you're clearing the correct Interval instead of hoping no other call has overwritten your variable.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号