gsap.timeline
is essentially a chain of tween (.to
, from
, fromTo
, etc.) calls. It is the ultimate sequencing tool that acts like a container for tweens and other timelines, making it simple to control them as a whole and precisely manage their timing. It is most similar to TimelineMax if you’re familiar with the GSAP 2.X syntax. The syntax is similar as TimelineMax in the 2.X version but with some improvements.
Without a timeline, building complex sequences would be far more cumbersome because you’d need to use the delay
special property for every tween. Here is a basic example:
gsap.to(element, {duration: 1, x: 100});
gsap.to(element, {duration: 1, y: 50, delay: 1});
gsap.to(element, {duration: 1, opacity: 0, delay: 2});
The above code animates the element to a translateX of 100px, then a translateY of 50px and finally its “opacity” to 0 (notice the delay
in all but the first tween). But what if you wanted to increase the duration of the first tween to 1.5? You’d need to adjust every delay thereafter. And what if you want to pause()
the whole sequence or restart()
it or reverse()
it on-the-fly or repeat it twice? This becomes quite messy (or flat-out impossible), but gsap.timeline
makes it incredibly simple:
var tl = gsap.timeline({repeat: 2, repeatDelay: 1});
tl.to(element, {duration: 1, x: 100});
tl.to(element, {duration: 1, y: 50});
tl.to(element, {duration: 1, opacity: 0});
//then later, control the whole thing...
tl.pause();
tl.resume();
tl.seek(1.5);
tl.reverse();
...
Or we could make use of the defaults
attribute of timeline and chaining to make our code even more concise:
var tl = gsap.timeline({repeat: 2, repeatDelay: 1, defaults: { duration: 1 } });
tl.to(element, {x: 100}).to(element, {y: 50}).to(element, {opacity: 0});
Now you can feel free to adjust any of the tweens without worrying about trickle-down changes to delays. Increase the duration of that first tween and everything automatically adjusts.
Here are some other benefits and features of gsap.timeline:
-
Things can overlap as much as you want. You have complete control over where tweens/timelines are placed using the position parameter. Most other animation tools can only do basic one-after-the-other sequencing but no overlaps.
-
Make use of the
defaults
attribute of timelines to pass default properties to all child tweens and timelines. For example://old way
TimelineMax
.to(obj, 1, {x: 50, ease: "Back.easeOut"})
.to(obj, 1, {x: 10, ease: "Back.easeOut"})
.to(obj, 1, {x: 150, ease: "Back.easeOut"})
//new way
gsap.timeline(defaults: {duration: 1, ease: "Back.easeOut"})
.to(obj, {x: 50})
.to(obj, {x: 10})
.to(obj, {x: 150})
-
Add labels, callbacks,
play()
,stop()
,seek()
,restart()
, and evenreverse()
smoothly anytime. -
Nest timelines within timelines as deeply as you want. This means you can modularize your code and make it far more efficient. Imagine building your app with common animateIn() and animateOut() methods that return a tween or timeline instance, then you can string things together like
myTimeline.add( myObject.animateIn() ).add( myObject.animateOut(), "+=4").add( myObject2.animateIn(), "-=0.5")...
. -
Speed up or slow down the entire timeline with its
timeScale()
method. You can even tween it to gradually speed up or slow down the animation smoothly. -
Get or set the progress of the timeline using its
progress()
ortotalProgress()
methods. For example, to skip to the halfway point, setmyTimeline.progress(0.5);
. -
Tween the
time()
,totalTime()
,progress()
, ortotalProgress()
to fast forward or rewind the timeline. You could even attach a slider to one of these to give the user the ability to drag forward or backward through the timeline. -
Add
onComplete
,onStart
,onUpdate
,onRepeat
and/oronReverseComplete
callbacks using the constructor’svars
object likevar tl = gsap.timeline({onComplete: myFunction});
. -
Kill the tweens of a particular object inside the timeline with
kill(null, target)
or get the tweens of an object withgetTweensOf()
or get all the tweens and timelines in the timeline withgetChildren()
. -
Set the timeline to repeat any number of times or indefinitely. You can even set a delay between each repeat cycle and/or cause the repeat cycles to yoyo, appearing to reverse direction every other cycle.
-
Get the active tweens in the timeline with
getActive()
. -
Get the
currentLabel()
or find labels at various positions in the timeline usingnextLabel()
andpreviousLabel()
. -
You can export all the tween and timelines from the root (master) timeline anytime into a timeline instance using
gsap.exportRoot()
so that you canpause()
them all orreverse()
or alter theirtimeScale
, etc. without affecting tweens/timelines that you create in the future. Imagine a game that has all its animation driven by the GreenSock Animation Platform and it needs to pause or slow down while a status screen pops up. Very easy.
Special Properties and Callbacks
You can optionally use the constructor’s vars
parameter to configure a timeline
with a variety of options.
gsap.timeline({onComplete: myFunction, repeat: 2, repeatDelay: 1, yoyo: true});
All of timeline’s vars
properties are described below:
CHANGE FORMAT below
-
autoRemoveChildren : Boolean - If
autoRemoveChildren
is set totrue
, as soon as child tweens/timelines complete, they will automatically get killed/removed. This is normally undesireable because it prevents going backwards in time (like if you want toreverse()
or set the progress lower, etc.). It can, however, improve speed and memory management. The root timelines useautoRemoveChildren: true
. -
callbackScope : Object - The scope to be used for all of the callbacks (
onStart
,onUpdate
,onComplete
, etc.). The scope is whatthis
refers to inside any of the callbacks. -
delay : Number - Amount of delay in seconds before the animation should begin.
-
onComplete : Function - A function that should be called when the animation has completed.
-
onCompleteParams : Array - An array of parameters to pass the
onComplete
function. For example,gsap.timeline({onComplete: myFunction, onCompleteParams: ["param1", "param2"]});
. -
onRepeat : Function - A function that should be called each time the animation repeats.
-
onRepeatParams : Array - An Array of parameters to pass the
onRepeat
function. For example,gsap.timeline({onRepeat: myFunction, onRepeatParams: ["param1", "param2"]});
. -
onReverseComplete : Function - A function that should be called when the animation has reached its beginning again from the reverse direction. For example, if
reverse()
is called the tween will move back towards its beginning and when itstime
reaches0
,onReverseComplete
will be called. This can also happen if the animation is placed in a timeline instance that gets reversed and plays the animation backwards to (or past) the beginning. -
onReverseCompleteParams : Array - An array of parameters to pass the
onReverseComplete
function. For example,gsap.timeline({onReverseComplete: myFunction, onReverseCompleteParams: ["param1", "param2"]});
. -
onStart : Function - A function that should be called when the animation begins (when its
time
changes from0
to some other value which can happen more than once if the tween is restarted multiple times). -
onStartParams : Array - An array of parameters to pass the
onStart
function. For example,gsap.timeline({onStart: myFunction, onStartParams: ["param1", "param2"]});
. -
onUpdate : Function - A function that should be called every time the animation updates (on every frame while the animation is active).
-
onUpdateParams : Array - An array of parameters to pass the
onUpdate
function. For example,gsap.timeline({onUpdate: myFunction, onUpdateParams: ["param1", "param2"]});
. -
paused : Boolean - If
true
, the animation will pause itself immediately upon creation. -
repeat : Number - Number of times that the animation should repeat after its first iteration. For example, if
repeat
is1
, the animation will play a total of twice (the initial play plus 1 repeat). To repeat indefinitely, use-1
.repeat
should always be an integer. -
repeatDelay : Number - Amount of time in seconds between repeats. For example, if
repeat
is2
andrepeatDelay
is1
, the animation will play initially, then wait for 1 second before it repeats, then play again, then wait 1 second again before doing its final repeat. -
smoothChildTiming : Boolean - Controls whether or not child tweens/timelines are repositioned automatically (changing their
startTime
) in order to maintain smooth playback when properties are changed on-the-fly. For example, imagine that the timeline’s playhead is on a child tween that is 75% complete, moving element’s left from 0 to 100 and then that tween’sreverse()
method is called. IfsmoothChildTiming
isfalse
(the default except for the root timelines), the tween would flip in place, keeping itsstartTime
consistent. Therefore the playhead of the timeline would now be at the tween’s 25% completion point instead of 75%. Remember, the timeline’s playhead position and direction are unaffected by child tween/timeline changes. element’s left would jump from 75 to 25, but the tween’s position in the timeline would remain consistent. However, ifsmoothChildTiming
istrue
, that child tween’sstartTime
would be adjusted so that the timeline’s playhead intersects with the same spot on the tween (75% complete) as it had immediately beforereverse()
was called, thus playback appears perfectly smooth. The element’s left would still be 75 and it would continue from there as the playhead moves on, but since the tween is reversed now element’s left will travel back towards 0 instead of 100. Ultimately it’s a decision between prioritizing smooth on-the-fly playback (true
) or consistent position(s) of child tweens/timelines (false
). Some examples of on-the-fly changes to child tweens/timelines that could cause theirstartTime
to change whensmoothChildTiming
istrue
are:reversed
,timeScale
,progress
,totalProgress
,time
,totalTime
,delay
,pause
,resume
,duration
, andtotalDuration
. -
useFrames : Boolean - If
useFrames
istrue
, the tweens’s timing will be based on frames instead of seconds because it is initially added to the root frames-based timeline. This causes both its duration and delay to be based on frames. An animations’s timing mode is always determined by its parent timeline. -
yoyo : Boolean - If
true
, every other repeat cycle will run in the opposite direction so that the tween appears to go back and forth (forward then backward). This has no affect on thereversed
property though. So ifrepeat
is2
andyoyo
isfalse
, it will look like: start - 1 - 2 - 3 - 1 - 2 - 3 - 1 - 2 - 3 - end. But ifyoyo
istrue
, it will look like: start - 1 - 2 - 3 - 3 - 2 - 1 - 1 - 2 - 3 - end.
Sample code:
//create the timeline that repeats 3 times with 1 second between each repeat and then calls myFunction() when it completes
var tl = gsap.timeline({repeat: 3, repeatDelay: 1, onComplete: myFunction});
//add a tween
tl.add( gsap.to(element, {duration: 1, x: 200, y: 100}) );
//add another tween 0.5 seconds after the end of the timeline (makes sequencing easy)
tl.to(element, {duration: 0.5, opacity: 0}, "+=0.5");
//reverse anytime
tl.reverse();
//Add a "spin" label 3-seconds into the timeline
tl.addLabel("spin", 3);
//insert a rotation tween at the "spin" label (you could also define the insertion point as the time instead of a label)
tl.to(element, {duration: 2, rotation: "+=360"}, "spin");
//go to the "spin" label and play the timeline from there
tl.play("spin");
//nest another timeline inside your timeline...
var nested = gsap.timeline();
nested.to(element2, {duration: 1, x: 200});
tl.add(nested);
How do timelines work? What are the mechanics like?
Every animation (tween and timeline) is placed on a parent timeline. In a sense, they all have their own playheads (that’s what its “time” refers to, or “totalTime” which is identical except that it includes repeats and repeatDelays) but generally they’re not independent because they’re sitting on a timeline whose playhead moves. When the parent’s playhead moves to a new position, it updates the childrens’ too.
When a timeline renders at a particular time, it loops through its children and says “okay, you should render as if your playhead is at __“ and if that child is a timeline with children, it does the same to its children, right on down the line.
The only exception is when the tween/timeline is paused in which case its internal playhead acts like it’s “locked”. So in that case, it’s possible (likely in fact) that the child’s playhead would not be synced with the parent’s. When you unpause it (resume()
), it essentially picks it up and moves it so that its internal playhead is synchronized with wherever the parent’s playhead is at that moment, thus things play perfectly smoothly. That is, unless the timeline’s smoothChildTiming
is false
in which case it won’t move - its startTime
will remain locked to where it was.
So basically when smoothChildTiming
is true
, the engine will rearrange things on the fly to ensure the playheads line up so that playback is seamless and smooth. The same thing happens when you reverse()
or alter the timeScale
, etc. But sometimes you might not want that behavior - you prefer to have tight control over exactly where your tweens line up in the timeline - that’s when smoothChildTiming: false
is handy.
One more example: let’s say you’ve got a 10-second tween that’s just sitting on the root timeline and you’re 2-seconds into the tween. Let’s assume it started at exactly 0 on the root to make this easy, and then when it’s at 2-seconds, you do tween.seek(5)
. The playhead of the root isn’t affected - it keeps going exactly as it always did, but in order to make that tween jump to 5 seconds and play appropriately, the tween’s startTime
gets changed to -3. That way, the tween’s playhead and the root playhead are perfectly aligned.
Notes
- If you need to access GSAP’s global timeline, you can do so using
gsap.globalTimeline
. This allows you to do things like pausing all animations (gsap.globalTimeline.pause();
) or slow all animations down (gsap.globalTimeline.timeScale(0.1);
). For more information. seegsap.globalTimeline
.