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!

Community
  • 1
  • 1
user219142
  • 39
  • 6
  • Possible duplicate of [How can I pass a parameter to a setTimeout() callback?](http://stackoverflow.com/questions/1190642/how-can-i-pass-a-parameter-to-a-settimeout-callback) – JJJ Dec 21 '15 at 22:39

2 Answers2

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.

Arnold Daniels
  • 16,516
  • 4
  • 53
  • 82
Senad Meškin
  • 13,597
  • 4
  • 37
  • 55
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.

Kristijan
  • 5,827
  • 1
  • 13
  • 21
  • Thanks - it is visual, but it's changing the co-ordinates of something(s) I'm moving around an html5 canvas. – user219142 Dec 22 '15 at 07:44
  • @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](http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/) – Kristijan Dec 22 '15 at 20:26