SetTimeout 不适用于递归。我做错了什么?

问题描述 投票:0回答:1

我需要一个函数使用递归每毫秒打印 1 到 10 的数字。 我的函数可能会打印从 2 到无穷大的数字,尽管写了退出递归的条件。我做错了什么?

 function printNumbers2(from, to) {
  let number = from;

  if (number == to) {
    return number;
  } else {
    return setTimeout(() => {
      console.log(number);
      number++;
      printNumbers2(number);
    }, 1000);
  }
}

console.log(printNumbers2(1, 10));

结果:

Timeout {
  _idleTimeout: 1000,
  _idlePrev: [TimersList],
  _idleNext: [TimersList],
  _idleStart: 15,
  _onTimeout: [Function (anonymous)],
  _timerArgs: undefined,
  _repeat: null,
  _destroyed: false,
  [Symbol(refed)]: true,
  [Symbol(kHasPrimitive)]: false,
  [Symbol(asyncId)]: 2,
  [Symbol(triggerId)]: 1
}
1
2
3
4
5
6
7
8
9
10
11
12
13
javascript recursion settimeout
1个回答
0
投票

您忘记在递归调用中传递“to”参数:

function printNumbers2(from, to) {
  let number = from;

  if (number == to) {
    return number;
  } else {
    return setTimeout(() => {
      console.log(number);
      number++;
      printNumbers2(number, to); // <-- pass in your "to" parameter
    }, 1000);
  }
}

console.log(printNumbers2(1, 10));
© www.soinside.com 2019 - 2024. All rights reserved.