繁体   English   中英

将参数传递给递归函数

[英]passing arguments into recursive functions

所以我有一个使用setTimeout()的递归函数,但我不知道如何继续将参数传递给setTimeout()所调用的递归函数。 我尝试使用.bind(null, time)并以这种方式传递参数,但它似乎不起作用。

我还尝试使用setTimeout可用的第三个选项,我认为该选项用于传递变量,但这似乎也不起作用。 我将尝试用我的代码示例进行解释...

我使用此功能的唯一方法是设置不同的超时延迟。

function delay(t) {
    return (500 - (t * pattern.length));
}

这就是给我造成麻烦的原因

function next(time) {
    //random code ~turn on//

    setTimeout(function() {
        //random code ~turn off//

        if(score < 50) { 
        setTimeout(next.bind(null, time), delay(time));
        }
    }, delay(time));
}

当我调用函数

next(30)

//random code ~turn on我的部分//random code ~turn on可以正常运行,但随后setTimeut函数几乎没有任何延迟地运行。 就像没有传递time变量(30)。控制台中也没有错误代码。

谢谢你的帮助!

我不确定是要尝试做复杂的事情还是要使简单的事情复杂化。 但是,按原样编写代码,最大的问题是您在遮住time参数:

function next(time) {
    //random code ~turn on//

    setTimeout(function(time) {
        // time is now undefined, because nothing is passed in
        // to to setTimeout third param


        if(score < 50) { 
         // time here no longer refers to the `time` passed into
         // next, but rather the undefined value delcared as a parameter 
         // to the callback to setTimeout.
         setTimeout(next.bind(null, time), delay(time));
        }
    }.bind(null, time), delay(time));
}

结果是您的超时以未定义的延迟被调用。 删除它可以使其正常工作(如果我了解您在做什么)。 您还可以将超时捕获中的time传递给超时,因此不需要绑定:

 // fake score and delay for demonstration purposes function delay(t) { return t; } function next(time) { setTimeout(function() { // don't pass a paran here (or if you do, rename it) let score = Math.random() console.log("running", score) if(score < .80) { setTimeout(next.bind(null, time), delay(time)); } }, delay(time)); } next(1000) 

暂无
暂无

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

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