Search code examples
javascripttiminggsap

How to call a function at different intervals in GSAP or Javascript?


I have a very basic slideshow as follows:

HTML

<div id="slideshow">
    <img class="slide" src="img/slideshow-1.png" >
    <img class="slide" src="img/slideshow-2.png" >
    <img class="slide" src="img/slideshow-3.png" >
</div>

JS

$(function(){

    var $slides = $(".slide");          //slides
    var currentSlide = 0;               //keep track on the current slide
    var stayTime = 3;                   //time the slide stays
    var slideTime = 1.3;                //fade in / fade out time

    TweenLite.set($slides.filter(":gt(0)"), {autoAlpha:0}); //we hide all images after the first one
    TweenLite.delayedCall(stayTime, nextSlide);             //start the slideshow

    function nextSlide(){                   
            TweenLite.to( $slides.eq(currentSlide), slideTime, {autoAlpha:0} );     //fade out the old slide
            currentSlide = ++currentSlide % $slides.length;                         //find out the next slide           
            TweenLite.to( $slides.eq(currentSlide), slideTime, {autoAlpha:1} );     //fade in the next slide
            TweenLite.delayedCall(stayTime, nextSlide);                             //wait a couple of seconds before next slide
    }

});

As you see it simply shows each image for 3 seconds (stayTime) and then fades it out. Suppose I want to keep the first image for 8 seconds, the second for 6.5 seconds and the third for 3 seconds. I mean stayTime is not the same for all images. How can I achieve that in GSAP or Javascript?


Solution

  • A solution could be to convert stayTime to an array, one item for each slide.

    var stayTime = [8, 6.5, 3];
    

    and then:

    TweenLite.delayedCall(stayTime[currentSlide], nextSlide);