簡體   English   中英

使用傳遞給函數的變量在 javascript 循環中添加延遲

[英]Adding a delay in a javascript loop with variables passed to the function

我正在嘗試構建一個延遲的循環函數。 我在這里找到了這個解決方案:

如何在 JavaScript 循環中添加延遲?

...但是因為我想多次使用該函數,所以我想將變量傳遞給該函數。 事實證明這很困難。 例如,假設我有一個名為“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); 
}

? 如果不應該,我錯了哪一點?

塔!

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

閱讀這篇關於 JS 中的閉包的文章以獲得更好的理解。

這里的限制是固定的。 我們使用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需要polyfill

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM