2

I'm trying to build a loop function with a delay. I've found this solution here:

How do I add a delay in a JavaScript loop?

...but because I want to use the function several times, I want to pass variables to the function. This is proving difficult. For example, say I've got a function called "animate_block" that I want to call with variable "blah". This function itself calls another function with this variable, then moves the variable forward by 1 until it reaches some limit, with a recursive setTimeout so it doesn't all happen at once. Should it look something like:

animate_block(blah)

function animate_block(ab_blah){
    move_block(ab_blah);
    ab_blah = ab_blah +1
    if(ab_blah <= 10){
        setTimeout(animate_block(){ab_blah},30); 
}

? And if it shouldn't which bit(s) have I got wrong?

Ta!

1

2 Answers 2

1

setTimeout takes a function as first argument. You can create a function on the fly, which has access to the ab_blah because functions have access to the parent scope.

animate_block(blah);

function animate_block(ab_blah) {
    move_block(ab_blah);
    ab_blah = ab_blah +1
    if (ab_blah <= 10) {
        setTimeout(function() { animate_block(ab_blah); }, 30); 
    }
}

Read this article on closures in JS to get a good understanding.

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

Comments

0

Here the limit is fixed. We use requestAnimationFrame instead of the 30ms timeout, as animate_block sounds like something visual.

function moveBlock(position) {
    'use strict';
    console.log('moving to block', position);
    return;
}

function animateBlock(position) {
    'use strict';
    //... in case the call was made with `position` higher then 10 it should not be executed
    if(position <= 10) {
        moveBlock(position);
        //we increase position, but `position++` returns `position` prior to the increment
        if (position++ < 10) {
            window.requestAnimationFrame(animateBlock.bind(animateBlock, position));
        }
    }
}

animateBlock(1);

Android < 4.4, IE8 and Opera Mini require a polyfill.

2 Comments

Thanks - it is visual, but it's changing the co-ordinates of something(s) I'm moving around an html5 canvas.
@user219142 With canvas requestAnimationFrame is recommended, if you’re running the animation loop in a tab that’s not visible, the browser won’t keep it running Paul Irish - requestAnimationFrame for Smart Animating

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.