Timing functions
This article is a part of my Web Animations article series.
Until now we defined our animations based on two things:
- a list of states of the animation with a progress value, for example:
- 0% → translateX(0px)
- 100% → translateX(300px) - the duration of an animation iteration, let’s say 2000ms
In summary we move an element 300px within 2 seconds.
Now the question: where should the element be after 1 second? The most intuitive answer would be 150px. The element moves with the same speed the whole 2 seconds. We call this a linear timing function.
It is obvious that there also must exist non-linear timing functions. This is the case when the element moves more pixels in the first half our animation duration than in the second half.
I made a visualization with two buttons with different timing functions. Both button take 2 seconds for a full animation. But note that the second button accelerates very quickly and slows down at the end.
The mathematical concept
You can see timing functions as a distortion of the animation progress value. The original progress value (derived from the passed time) gets transformed into a progress value to display.
Think of our 2 second animation with 300px movement and we want calculate the position “500ms after the start of the animation”.
First we compute the progress value:
progress = timePassed / animationDuration
= 500 / 2000
= 0.25
Without timing function
Without a non-linear timing function we would just multiply the progress value with the pixels to move.
deltaMovement = progress * 300px
= 0.25 * 300px
= 75px
We now know that our element should be 75px rightwards from the starting position.
With timing function
Now we recalculate our example with a non-linear function that accelerates at the beginning and slows down at the end.
We assume this timing function to be something like this:
progress = timingFunction(progress)
= timingFunction(0.25)
= 0.4deltaMovement = progress * 300px
= 0.4 * 300px
= 120px
By modifying the progress value we get position that far more rightwards. When we constantly doing this for each point in time it appears to be accelerating and breaking.
Built-in timing functions
When the browser manages the animation you can specify the timing function with the
transition-timing-function
property when using CSS Transitionanimation-timing-function
property when using CSS Animation
The default value is ease
which means a slow start, then fast and a slow end. There are some variation called ease-in
(only slow start) and ease-out
(only slow end). Of course the value linear
exists as well.
The
ease-out
would mostly match our non-linear timing function we assumed in our example above.
There are several more values for built-in timing functions. Let us see them in action:
Now you have a deep understanding of timing functions. We will use this knowledge when we come to dynamic animations.