2015-12-21 70 views
2

我试图建立一个有延迟的循环函数。我发现这个解决方案在这里:添加延迟在一个JavaScript循环中传递给函数的变量

How do I add a delay in a JavaScript loop?

...但因为我想使用的功能好几次,我想传递变量的函数。这证明很困难。例如,假设我有一个名为“animate_block”的函数,我想用变量“blah”调用。该函数本身使用该变量调用另一个函数,然后将该变量向前移动1,直到达到某个极限,并使用递归setTimeout,因此它不会一次全部发生。应该看起来像这样:

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); 
} 

?如果它不应该哪个位有我错了?

Ta!

+0

可能重复的[我如何将参数传递给setTimeout()回调?](http://stackoverflow.com/questions/1190642/how-can-i-pass-a-parameter-toa-a- settimeout-callback) – JJJ

回答

1

setTimeout将函数作为第一个参数。您可以随时创建一个函数,该函数可以访问ab_blah,因为函数可以访问父范围。

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); 
    } 
} 

阅读this article on closures in JS以获得良好的理解。

+0

完美 - 谢谢! – user219142

0

这里的限制是固定的。我们使用requestAnimationFrame而不是30ms超时,因为animate_block听起来像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和Opera Mini的require一个polyfill

+0

谢谢 - 它是可视化的,但它改变了我在html5画布上移动的东西的坐标。 – user219142

+0

@ user219142建议使用canvas'requestAnimationFrame', '''如果您在不可见的选项卡中运行动画循环,浏览器将不会保持运行''' [Paul Irish - requestAnimationFrame for智能动画](http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/) – Kristijan