2015-12-21 76 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