简体   繁体   English

使用传递给函数的变量在 javascript 循环中添加延迟

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

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? 如何在 JavaScript 循环中添加延迟?

...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".例如,假设我有一个名为“animate_block”的函数,我想用变量“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.这个函数本身使用这个变量调用另一个函数,然后将变量向前移动 1 直到它达到某个限制,使用递归 setTimeout 所以它不会同时发生。 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!塔!

setTimeout takes a function as first argument. setTimeout将函数作为第一个参数。 You can create a function on the fly, which has access to the ab_blah because functions have access to the parent scope.您可以动态创建一个函数,它可以访问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); 
    }
}

Read this article on closures in JS to get a good understanding.阅读这篇关于 JS 中的闭包的文章以获得更好的理解。

Here the limit is fixed.这里的限制是固定的。 We use requestAnimationFrame instead of the 30ms timeout, as animate_block sounds like something visual .我们使用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 and Opera Mini require a polyfill . Android < 4.4、IE8 和 Opera Mini需要polyfill

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM