简体   繁体   English

将参数传递给递归函数javaScript

[英]passing arguments to a recursive function javaScript

I understood that the best practice with setTimeOut is sending an anonymous function with the function I want to redo inside. 我知道setTimeOut的最佳实践是发送一个匿名函数,其中包含我想要重做的函数。 Why won't it work? 为什么它不起作用?

function movement(dir) {
    ...
    ...
        setTimeOut(function (){movement(dir);},21);

It will work. 它会工作。 Of course, the name of the function is setTimeout() instead of setTimeOut() . 当然,函数的名称是setTimeout()而不是setTimeOut() See this example: 看这个例子:

function movement(dir) {
  console.log(dir);
  if (dir++ < 5) {
    setTimeout(function () {
      movement(dir);
    }, 21);
  }
};

movement(1);

It prints: 它打印:

1
2
3
4
5

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

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