setInterval not working properly on Chrome

前端 未结 4 716
轻奢々
轻奢々 2020-11-30 07:11

I have a custom made slideshow object to perform the usual stuff the name indicates on a website. It all works well except when I switch tabs in Chrome and come back to the

4条回答
  •  野性不改
    2020-11-30 07:46

    Chrome (and apparently the latest versions of Firefox too) reduce the speed of setInterval when the tab is in the background to improve foreground performance. This probably matters the most when there are fast running timer-driven animations in background pages. When the page comes back to the foreground, it "tries" to catch up and runs a bunch of setInterval calls much faster than they would normally run.

    The work-arounds are:

    1. Lengthen the time of the setInterval so Chrome won't mess with it (you'd have to look up what that time is).
    2. Stop your interval timer when the page goes in the background (no need to run slides when it's not visible anyway) - then start it up again when the page comes to the foreground.
    3. Use repeated setTimeout instead of setInterval with some type of repeated setTimeout like this:

    Code:

    function nextSlide() {
        // show next slide now
        // set timer for the slide after this one
        setTimeout(function() {
            nextSlide();       // repeat
        }, xxx)
    }
    

    Similar post here.

提交回复
热议问题