Jump to content
GreenSock

Search In
  • More options...
Find results that contain...
Find results in...

Timeline

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:

  1. gsap.to(element, {duration: 1, x: 100});
  2. gsap.to(element, {duration: 1, y: 50, delay: 1});
  3. 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:

  1. var tl = gsap.timeline({repeat: 2, repeatDelay: 1});
  2. tl.to(element, {duration: 1, x: 100});
  3. tl.to(element, {duration: 1, y: 50});
  4. tl.to(element, {duration: 1, opacity: 0});
  5. //then later, control the whole thing...
  6. tl.pause();
  7. tl.resume();
  8. tl.seek(1.5);
  9. tl.reverse();
  10. ...

Or we could make use of the defaults attribute of timeline and chaining to make our code even more concise:

  1. var tl = gsap.timeline({repeat: 2, repeatDelay: 1, defaults: { duration: 1 } });
  2. 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:

    1. //old way
    2. TimelineMax
    3. .to(obj, 1, {x: 50, ease: "Back.easeOut"})
    4. .to(obj, 1, {x: 10, ease: "Back.easeOut"})
    5. .to(obj, 1, {x: 150, ease: "Back.easeOut"})
    6. //new way
    7. gsap.timeline(defaults: {duration: 1, ease: "Back.easeOut"})
    8. .to(obj, {x: 50})
    9. .to(obj, {x: 10})
    10. .to(obj, {x: 150})
  • Add labels, callbacks, play(), stop(), seek(), restart(), and even reverse() 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() or totalProgress() methods. For example, to skip to the halfway point, set myTimeline.progress(0.5);.

  • Tween the time(), totalTime(), progress(), or totalProgress() 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/or onReverseComplete callbacks using the constructor’s vars object like var 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 with getTweensOf() or get all the tweens and timelines in the timeline with getChildren().

  • 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 using nextLabel() and previousLabel().

  • You can export all the tween and timelines from the root (master) timeline anytime into a timeline instance using gsap.exportRoot() so that you can pause() them all or reverse() or alter their timeScale, 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.

  1. 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 to true, 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 to reverse() or set the progress lower, etc.). It can, however, improve speed and memory management. The root timelines use autoRemoveChildren: true.

  • callbackScope : Object - The scope to be used for all of the callbacks (onStart, onUpdate, onComplete, etc.). The scope is what this 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 its time reaches 0, 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 from 0 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 is 1, 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 is 2 and repeatDelay is 1, 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’s reverse() method is called. If smoothChildTiming is false (the default except for the root timelines), the tween would flip in place, keeping its startTime 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, if smoothChildTiming is true, that child tween’s startTime would be adjusted so that the timeline’s playhead intersects with the same spot on the tween (75% complete) as it had immediately before reverse() 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 their startTime to change when smoothChildTiming is true are: reversed, timeScale, progress, totalProgress, time, totalTime, delay, pause, resume, duration, and totalDuration.

  • useFrames : Boolean - If useFrames is true, 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 the reversed property though. So if repeat is 2 and yoyo is false, it will look like: start - 1 - 2 - 3 - 1 - 2 - 3 - 1 - 2 - 3 - end. But if yoyo is true, it will look like: start - 1 - 2 - 3 - 3 - 2 - 1 - 1 - 2 - 3 - end.

Sample code:

  1. //create the timeline that repeats 3 times with 1 second between each repeat and then calls myFunction() when it completes
  2. var tl = gsap.timeline({repeat: 3, repeatDelay: 1, onComplete: myFunction});
  3. //add a tween
  4. tl.add( gsap.to(element, {duration: 1, x: 200, y: 100}) );
  5. //add another tween 0.5 seconds after the end of the timeline (makes sequencing easy)
  6. tl.to(element, {duration: 0.5, opacity: 0}, "+=0.5");
  7. //reverse anytime
  8. tl.reverse();
  9. //Add a "spin" label 3-seconds into the timeline
  10. tl.addLabel("spin", 3);
  11. //insert a rotation tween at the "spin" label (you could also define the insertion point as the time instead of a label)
  12. tl.to(element, {duration: 2, rotation: "+=360"}, "spin");
  13. //go to the "spin" label and play the timeline from there
  14. tl.play("spin");
  15. //nest another timeline inside your timeline...
  16. var nested = gsap.timeline();
  17. nested.to(element2, {duration: 1, x: 200});
  18. 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. see gsap.globalTimeline.

Properties

autoRemoveChildren : Boolean

If true, child tweens and timelines will be removed as soon as they complete.

data : *

A place to store any data you want (initially populated with vars.data if it exists).

labels : Array

This stores any labels that have been added to the timeline.

smoothChildTiming : Boolean

Controls whether or not child tweens and timelines are repositioned automatically (changing their startTime) in order to maintain smooth playback when properties are changed on-the-fly.

Methods

add( value:*, position:*, align:String, stagger:Number ) : *

[override] Adds a tween, timeline, callback, or label (or an array of them) to the timeline.

addLabel( label:String, position:* ) : *

Adds a label to the timeline, making it easy to mark important positions/times.

addPause( position:*, callback:Function, params:Array, scope:* ) : *

Inserts a special callback that pauses playback of the timeline at a particular time or label.

call( callback:Function, params:Array, position:* ) : *

Adds a callback to the end of the timeline (or elsewhere using the position parameter) - this is a convenience method that accomplishes exactly the same thing as add( gsap.delayedCall(...) ) but with less code.

clear( labels:Boolean ) : *

Empties the timeline of all tweens, timelines, and callbacks (and optionally labels too).

currentLabel( value:String ) : *

Gets the closest label that is at or before the current time, or jumps to a provided label (behavior depends on whether or not you pass a parameter to the method).

delay( value:Number ) : *

Gets or sets the animation's initial delay which is the length of time in seconds before the animation should begin.

duration( value:Number ) : *

[override] Gets the timeline's duration or, if used as a setter, adjusts the timeline's timeScale to fit it within the specified duration.

endTime( includeRepeats:Boolean ) ;

Returns the time at which the animation will finish according to the parent timeline's local time.

eventCallback( type:String, callback:Function, params:Array, scope:* ) : *

Gets or sets an event callback like onComplete, onUpdate, onStart, onReverseComplete, or onRepeat along with any parameters that should be passed to that callback.

from( target:Object, vars:Object, position:* ) : *

Adds a .from() tween to the end of the timeline (or elsewhere using the position parameter) - this is a convenience method that accomplishes exactly the same thing as add( gsap.from(...) ) but with less code.

fromTo( target:Object, fromVars:Object, toVars:Object, position:* ) : *

Adds a .fromTo() tween to the end of the timeline - this is a convenience method that accomplishes exactly the same thing as add( gsap.fromTo(...) ) but with less code.

getChildren( nested:Boolean, tweens:Boolean, timelines:Boolean, ignoreBeforeTime:Number ) : Array

Returns an array containing all the tweens and/or timelines nested in this timeline.

getTweensOf( target:Object, nested:Boolean ) : Array

Returns the tweens of a particular object that are inside this timeline.

invalidate( ) : *

[override] Flushes any internally-recorded starting/ending values which can be useful if you want to restart an animation without reverting to any previously recorded starting values.

isActive( ) : Boolean

Indicates whether or not the animation is currently active (meaning the virtual playhead is actively moving across this instance's time span and it is not paused, nor are any of its ancestor timelines).

iteration( value:Number ) : *

Gets or sets the iteration (the current repeat) of timelines.

kill( vars:Object, target:Object ) : *

Kills the animation entirely or in part depending on the parameters.

nextLabel( time:Number ) : String

Returns the next label in the timeline from the provided time. If no <code>time</code> is provided, the timeline's current playhead time will be used.

Powered by Froala Editor

pause( atTime:*, suppressEvents:Boolean ) : *

Pauses the instance, optionally jumping to a specific time.

paused( value:Boolean ) : *

Gets or sets the animation's paused state which indicates whether or not the animation is currently paused.

play( from:*, suppressEvents:Boolean ) : *

Begins playing forward, optionally from a specific time (by default playback begins from wherever the playhead currently is).

previousLabel( time:Number ) : String

Returns the label name before the time provided. If no time

progress( value:Number, suppressEvents:Boolean ) : *

[override] Gets or sets the timeline's progress which is a value between 0 and 1 indicating the position of the virtual playhead (excluding repeats) where 0 is at the beginning, 0.5 is halfway complete, and 1 is complete.

recent( ) : *

Returns the most recently added child tween/timeline/callback regardless of its position in the timeline.

remove( value:* ) : *

Removes a tween, timeline, callback, or label (or array of them) from the timeline.

removeLabel( labels:String ) : *

Removes a label from the timeline and returns the time of that label.

removePause( position:* ) : *

Removes pauses that were added to a timeline via gsap.addPause().

repeat( value:Number ) : *

Gets or sets the number of times that the timeline should repeat after its first iteration.

repeatDelay( value:Number ) : *

Gets or sets the amount of time in seconds (or frames for frames-based timelines) between repeats.

restart( includeDelay:Boolean, suppressEvents:Boolean ) : *

Restarts and begins playing forward from the beginning.

resume( from:*, suppressEvents:Boolean ) : *

Resumes playing without altering direction (forward or reversed), optionally jumping to a specific time first.

reverse( from:*, suppressEvents:Boolean ) : *

Reverses playback so that all aspects of the animation are oriented backwards including, for example, a tween's ease.

reversed( value:Boolean ) : *

Gets or sets the animation's reversed state which indicates whether or not the animation should be played backwards.

seek( position:*, suppressEvents:Boolean ) : *

[override] Jumps to a specific time (or label) without affecting whether or not the instance is paused or reversed.

set( target:Object, vars:Object, position:* ) : *

Adds a zero-duration tween to the end of the timeline (or elsewhere using the position parameter) that sets values immediately when the virtual playhead reaches that position on the timeline - this is a convenience method that accomplishes exactly the same thing as add( gsap.to(target, {duration: 0, ...}) ) but with less code.

shiftChildren( amount:Number, adjustLabels:Boolean, ignoreBeforeTime:Number ) : *

Shifts the startTime of the timeline's children by a certain amount and optionally adjusts labels too.

startTime( value:Number ) : *

Gets or sets the time at which the animation begins on its parent timeline (after any delay that was defined).

then( callback:Function ) : Promise

Returns a promise so that you can uses promises to track when a tween or timeline is complete.

time( value:Number, suppressEvents:Boolean ) : *

[override] Gets or sets the local position of the playhead (essentially the current time), not including any repeats or repeatDelays.

timeScale( value:Number ) : *

Factor that's used to scale time in the animation where 1 = normal speed (the default), 0.5 = half speed, 2 = double speed, etc.

to( target:Object, vars:Object, position:* ) : *

Adds a gsap.to() tween to the end of the timeline (or elsewhere using the position parameter) - this is a convenience method that accomplishes exactly the same thing as add( gsap.to(...) ) but with less code.

totalDuration( value:Number ) : *

[override] Gets or sets the total duration of the timeline in seconds including any repeats or repeatDelays.

Powered by Froala Editor

totalProgress( value:Number, suppressEvents:Boolean ) : *

[override] Gets or sets the timeline's total progress which is a value between 0 and 1 indicating the position of the virtual playhead (including repeats) where 0 is at the beginning, 0.5 is at the halfway point, and 1 is at the end (complete).

totalTime( time:Number, suppressEvents:Boolean ) : *

Gets or sets the position of the playhead according to the totalDuration which includes any repeats and repeatDelays.

tweenFromTo( fromPosition:*, toPosition:*, vars:Object ) : Tween

Creates a linear tween that essentially scrubs the playhead from a particular time or label to another time or label and then stops.

tweenTo( position:*, vars:Object ) : Tween

Creates a linear tween that essentially scrubs the playhead to a particular time or label and then stops.

yoyo( value:Boolean ) : *

Gets or sets the timeline's yoyo state, where true causes the timeline to go back and forth, alternating backward and forward on each repeat.

Copyright 2017, GreenSock. All rights reserved. This work is subject to theterms of useor for Club GreenSock members, the software agreement that was issued with the membership.
×