When using setInterval, if I switch tabs in Chrome and go back, the slider goes crazy catching up

前端 未结 6 686
醉话见心
醉话见心 2020-11-28 05:05

I have a jQuery slider on my site and the code going to the next slide is in a function called nextImage. I used setInterval to run my function on a timer, and it does exact

6条回答
  •  -上瘾入骨i
    2020-11-28 05:45

    How to detect when a tab is focused or not in Chrome with Javascript?

    window.addEventListener('focus', function() {
        document.title = 'focused';
    },false);
    
    window.addEventListener('blur', function() {
        document.title = 'not focused';
    },false);
    

    To apply to your situation:

    var autopager;
    function startAutopager() {
        autopager = window.setInterval(nextImage, 8000);
    }
    function stopAutopager() {
        window.clearInterval(autopager);
    }
    
    window.addEventListener('focus', startAutopager);    
    window.addEventListener('blur', stopAutopager);
    

    Note that in the latest version of Chromium, there is either a bug or a 'feature' which is making this less reliable, requiring that the user has clicked at least once anywhere in the window. See linked question above for details.

提交回复
热议问题