Jump to content
Search Community

How to create random repeatDelay

alx test
Moderator Tag

Go to solution Solved by mvaneijgen,

Recommended Posts

Greetings!

I can't figure out how to implement a random repeatDelay on this simple animation:

gsap.timeline({
  repeat: -1,
  repeatDelay: 'random(1, 5)',
})

  .to('.dot', {   
  ease: 'none',
  duration: 1,
  y: '100vh',
  onComplete() {
    gsap.set('.dot', {
      x: 'random(100, 1000)', 
      ease: 'none',
    })
  }
});

As you can see, in this simple version of the animation, it's just a dot that starts from random x points at the top and simply falls to the bottom and repeats infinitely. It works fine. But I need the repeatDelay to be random and I thought I could use random for the repeatDelay but I'm obviously doing some wrong...

See the Pen eYaRLRj by alxhrrs (@alxhrrs) on CodePen

Link to comment
Share on other sites

  • Solution

GSAP is highly optimised and will 'bake' all the animations/values on first load, so that it only has to focus on animating the elements. So on page load it gets a new random value and then used that value when ever, but the utils random function has an option to create a function of it and if you use this in the onComplete callback to set a new repeatDelay value it will work as you expect  https://gsap.com/docs/v3/GSAP/UtilityMethods/random()/

 

I've written it out really verbose, so that you can see the value updating in the console, but you can just feed in the random function directly. Hope it helps and happy tweening! 

 

See the Pen WNBEeKL?editors=0011 by mvaneijgen (@mvaneijgen) on CodePen

  • Like 3
  • Thanks 1
Link to comment
Share on other sites

Glad to hear @mvaneijgen's solution worked for you. There's absolutely nothing wrong with it.

 

Here is an alternate solution that isn't any better or worse but it's what I usually reach for. 

 

I was already working on it so figured I'd post anyway.

 

The basic idea is that you create a function that creates a tween that contains an onComplete that calls the function again at a random interval

 

See the Pen xxNLbwa?editors=0010 by snorkltv (@snorkltv) on CodePen

 

Going one step further you could tell the function which element to drop and now you have multiple elements following the same procedure

 

See the Pen KKLvwMq?editors=1010 by snorkltv (@snorkltv) on CodePen

 

 

  • Like 4
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...