Detecting if Anything on the Page is being Animate

2020-03-06 03:46发布

问题:

I know about the :animated selector, but currently am running into (what might be one of a few) performance issue for older IE's (go figure). I feel like it might potentially be the way I'm testing for ANY Page Animation.

Currently I'm looping through an interval, with the core test being $('*').is(':animated'). This $('*') is what i'm worried about... but since I don't know exaclty what the divs / etc are that are being animated below my plugin, I'm not sure how else to do it!

var testAnimationInterval = setInterval(function () {

    if ( ! $('*').is(':animated') ) {  // all done animating
        clearInterval(testAnimationInterval);

        animationsFinished();  // callback function
    }
}, 300);

function animationsFinished() {
    // do whatever
}

Has anyone found a better / different way of doing this? Especially when it comes to performance?

回答1:

All jQuery animation timers are stored in the array $.timers. One option is just to check whether length of $.timers property is more than zero:

if ($.timers.length > 0) {
    // something is animating
}


回答2:

I think it would be more efficient to push your element to an array when the animation starts, and remove it from the array when it's done animating. Or better yet, increment a variable on animation start, and decrease it by 1, when it's done. If the variable is 0, no animation should currently be running.

So, some pseudocode:

var animatingElements = 0;

function animationStart(){ // Add this function in your animation start events;
    animatingElements++;
}

function animationEnd(){ // Add this function  in your animation end events;
    animatingElements--;
}

if (animatingElements === 0) {
    clearInterval(testAnimationInterval);
}

This is, assuming you have access to the code that starts / catches the end of your animations, of course.