Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Measuring time for CSS3 to finish animations

I'm trying to compare CSS3 animations with Javascript animations, and I'm trying to measure the time it takes to complete a CSS3 animation. Using Chrome's Timeline tool, the actual time is always longer than the time that I specified in CSS3. Is there a method to automatically get the time elapsed instead of manually using the Timeline tool?

like image 770
Leo Jiang Avatar asked Nov 01 '22 07:11

Leo Jiang


1 Answers

Edit

In brief

You'll have to use timestamps AFAIK.

Depending on what you're trying to observe, you can either see the real time Javascript takes to trigger a CSS animation, or see the real time elapsed of the CSS animation.

In details

As we've seen, elapsedTime is not sufficient to get the real time elapsed.

Using timestamps (Date.now() and event.timeStamp), I determined the real time elapsed for the animation & the time elapsed between animation trigger and animationEnd event:

  • Save current timestamp when adding the animating class in Javascript,
  • Save the timestamp in animationStart,
  • Save the timestamp in animationEnd,
  • Compare those timestamp.

Here is the result of my tests on this fiddle:

Debugger Timeline

console.log('Time elapsed between animation trigger and AnimationEnd : ' + (animationEndTimestamp - animationTriggeredTimestamp) + 'ms');
console.log('Time Animation took really ' + (animationEndTimestamp - animationStartTimestamp) + 'ms');

We can see that javascript takes ± 4.3 seconds to recalculate the style, and then the animationStart event is triggered. The former takes exactly 2874ms to recalculate and layout. So that match the timeline, no need for it anymore.

Note: I've run this test with 10, 100, 1000, 10000 & 20000 divs.


Old answer

Interesting question!

You could use a listener for CSS3's ended animation event, called animationend (vendor-prefixes applies) :

yourElement.addEventListener("animationend", animationListener, false);

And then use one of AnimationEvent's properties, elapsedTime :

AnimationEvent.elapsedTime (Read only)

Is a float giving the amount of time the animation has been running, in seconds, when this event fired, excluding any time the animation was paused.

For an animationstart event, elapsedTime is 0.0 unless there was a negative value for animation-delay, in which case the event will be fired with elapsedTime containing (-1 * delay).

References :

  • AnimationEvent on MDN,
  • The article I stumbled upon,
  • and here for an example.
  • Current vendor prefixes :
    • animationend
    • webkitAnimationEnd
    • MSAnimationEnd
    • oAnimationEnd
like image 162
Bigood Avatar answered Nov 15 '22 03:11

Bigood