简体   繁体   中英

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. 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() . 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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