3

Is there a way to put those five setTimeouts into one setInterval? I need to somehow switch the parameter of the function after each interval. Basically, I want to be able to clear the animation without having to clear 5 setTimeouts. Here is the anim. www.hodaradesign.com. thanks!

<script type="text/javascript">
$(window).load(function () {
    setTimeout ("pulse('1')", 300); 
    setTimeout ("pulse('2')", 500); 
    setTimeout ("pulse('3')", 700); 
    setTimeout ("pulse('4')", 900); 
    setTimeout ("pulse('5')", 1100); 
});

function pulse(n) { 
    $(".roll"+n).animate({"opacity": "0"}, 650);
    setTimeout (function (){
        $(".roll"+n).animate({"opacity": "1"}, 350);
    },800)
};

</script>

3 Answers 3

1

Try this:

<script type="text/javascript">
$(window).load(function () {
        var iCounter = 1; //variable to keep track of current iteration.
        var interValKey = null;//variable to store the key to clear the interval later.
        setTimeout (function(){
            interValKey = setInterval(function(){
                pulse(iCounter); 
                iCounter++;
                if(iCounter == 6){
                clearInterval(interValKey);
                }
            }, 200);
        }, 300); 
});

function pulse(n) { 
    $(".roll"+n).animate({"opacity": "0"}, 650);
    setTimeout (function (){
        $(".roll"+n).animate({"opacity": "1"}, 350);
    },800)
};

</script>
Sign up to request clarification or add additional context in comments.

Comments

1

Use a variable that both the setInterval call and the function can access.

<script type="text/javascript">
var n = 1;

$(window).load(function () {
    setTimeout(function() {
        setInterval(pulse, 200);
    }, 300);
});

function pulse() {
    var current_n = n; // avoid a race condition
    $(".roll" + current_n).animate({"opacity": "0"}, 650);
    setTimeout (function (){
        $(".roll" + current_n).animate({"opacity": "1"}, 350);
    }, 800);

    n += 1;
};

</script>

Comments

0

Add another parameter to the script to specify the current timeout, then use the function itself to increment the count and determine when (and if) the next invocation occurs.

<script type="text/javascript">
$(window).load(function () {
    setTimeout( function() { pulse(1,200); }, 300 ); 
});

function pulse(n,time) { 
    if (n <= 5) {
       setTimeout( function() { pulse(n+1,time); }, time );
    }

    $(".roll"+n).animate({"opacity": "0"}, 650);
    setTimeout (function (){
        $(".roll"+n).animate({"opacity": "1"}, 350);
    },800);

};

</script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.