Is there a way to know when the browser is actively running requestAnimationFrame?

For example when I switch tabs from one that was running requestAnimationFrame, the function stops getting executed, when I switch back it continues, what is the best way to deal with this?

有帮助吗?

解决方案

To detect if requestAnimationFrame is running 100% you can check:

window.addEventListener('blur', function() {
   //not running full
}, false);

and

window.addEventListener('focus', function() {
   //running optimal (if used)
}, false);

this can be used as we know requestAnimationFrame reduces trigger rate (in most browsers) when window (tab) is not the active one (IF being used - it depends on the code actually using the requestAnimationFrame).

If you want it to run constantly you can insert a mechanism such as this:

var isActiveTab = true; //update with the events above

function myLoop() {

    //my cool stuff here

    if (isActiveTab) {
         requestAnimationFrame(myLoop);
    } else {
         setTimeout(myLoop, 16); //force a rate (vblank sync not necessary
                                 //when display isn't updated
    }
}

Note that the reduction in rate for requestAnimationFrame is not part of the standard and is a browser specific implementation.

其他提示

When you again come back to the tab with animation,It must be working fine(If thats the case--following is your answer!!!)

This is what RAF made for.To optimize performance. SetInterval and Settimeout can be used instead for creating animations, But they cannot interact with the browser and eventually end up hogging up the cpu and the performance is also quite slow.

But your question is really not a question.This is actually a trick used by RAF to better your overall animation experience.

There are several articles which explains RAF. http://creativejs.com/resources/requestanimationframe/

Just An Optimization TRICK--No need to worry about it

A solution I used in a project for canvas repainting. It's not 100% accurate but it works for out of focus users

// This will run when user is inactive
let = handleVisibilityChange = () => {
    if (document.hidden) {
        setTimeout(() => {
            updateYourStuff();
            handleVisibilityChange();
        }, 1000);
    }
};

// Listen if user is active or inactive
document.addEventListener("visibilitychange", handleVisibilityChange, false);

// Your loop when user is active
function myLoop() {
    updateYourStuff();
    requestAnimationFrame(myLoop);
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top