2

i have these scrip that i need to loop:

$(document).ready(function() {
    runIt();
})
function resets()
{
  $('.grower').removeAttr("style");
}

function runIt() 
    {
        $('.grower').animate({width: "30px",height: '30px', left: "-6", top: "-6", opacity:"0"}, 800, resets);
    }

but when i add the runIt(); inside it self so it can loop, it loops but my browser goes blank and i will not respond. how can i do it so it will loop that animation.

thanks in advance

2 Answers 2

9

No need to query the DOM constantly. Store the $('.grower') in a variable:

$(document).ready(function() {
    var $grower = $('.grower');

    function runIt() {
        $grower.animate({
            width: "30px",
            height: '30px',
            left: "-6",
            top: "-6",
            opacity:"0"
        }, 800, function() {
            $grower.removeAttr("style");
            runIt();
        });
    }

    runIt();
});

Here's the fiddle: http://jsfiddle.net/jC8Js/


Update: If you want it to pause before each cycle, use a timer:

setTimeout(runIt, 1000);

Here's the fiddle: http://jsfiddle.net/jC8Js/1/


Alternatively, you could just run all of it with an interval timer:

$(document).ready(function() {
    var $grower = $('.grower');

    setInterval(function() {
        $grower.animate({
            width: "30px",
            height: '30px',
            left: "-6",
            top: "-6",
            opacity:"0"
        }, 800, function() {
            $grower.removeAttr("style");
        });
    }, 1500);
});​

Here's the fiddle: http://jsfiddle.net/jC8Js/2/

Sign up to request clarification or add additional context in comments.

3 Comments

@YairVillar - I added some code to pause it after it loops each time.
This: function runIt() { ... runIt(); } can cause stack overflow, because there is no stop condition. It won't show up until many "iterations", but I run into an issue with a similar approach when using jquery transition() (instead on animate()) on IE9, which does not support css transitions. The sub-call was immediate, the stack run out fast. I think this recurrent approach is not exactly how this loop should be done.
@kuonirat - In that case, use setInterval, as shown in the 2nd example. Though once we get tail call optimization I don't think this will be a problem.
1

http://jsfiddle.net/nUVbb/

 $(document).ready(function() {
    runIt();
})
function resets()
{
    $('.grower').removeAttr("style");
    runIt();
}
function runIt() 
{
    $('.grower').animate({width: "30px",height: '30px', left: "-6", top: "-6", opacity:"0"}, 800, resets);
}

2 Comments

how can i give it time after it loops each time??
add .delay(500) before .animate()

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.