Jump to content
Search Community

how to randomise timing of repeated animation

robwebb364 test
Moderator Tag

Go to solution Solved by Carl,

Warning: Please note

This thread was started before GSAP 3 was released. Some information, especially the syntax, may be out of date for GSAP 3. Please see the GSAP 3 migration guide and release notes for more information about how to update the code to GSAP 3's syntax. 

Recommended Posts

The codepen has two black rectangles which appear and then disappear.


One has an onComplete function which randomises the time variable,

but this does not work.. the timing remains the same.


How might one do this?

Presumably we need to stop the repeat, reset the time, and restart it?


Thanks for help.

See the Pen joGCh by robertwebb364 (@robertwebb364) on CodePen

Link to comment
Share on other sites

  • Solution

Hi and thanks for providing the demos.


Having 2 separate timelines is definitely a more manageable approach. Otherwise you would have to target the tween inside the timeline and change its duration repeatedly. Using the time variable as the duration and changing it repeatedly is not sufficient as that only gets read ONCE when the tween is created.


Also, please add a console.log("timerand()") to your timerand() function. You will see that it only fires once when the page first loads in your latest pen.


Note you need to make the following change:



tl.to("#p2", time, {opacity:1, ease:Power1.easeIn, onComplete:timerand()}) //do not use () this forces the function to be called when the tween is created



tl.to("#p2", time, {opacity:1, ease:Power1.easeIn, onComplete:timerand}) //this passes a reference to the timerand function to the onComplete callback


BTW, that is a very common mistake. Nothing to worry about.


Here is a revised version that has a single repeating timeline that changes its timeScale() when it repeats:


var tl = new TimelineMax({repeat:-1});
tl.to("#p2", time, {opacity:1, x:200, ease:Power1.easeIn, onComplete:timerand})

function timerand(){
  var time=(Math.floor(Math.random()*(2 - 0.5 +1))+ 0.5);



Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Create New...