Search code examples
javascriptcanvasrequestanimationframe

requestAnimationFrame and knowing when the browser is re-painting?


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?


Solution

  • 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.