从 Javascript 中的 setTimeout 中的函数获取返回的项目

Get returned items from function inside setTimeout in Javascript

所以我需要在我的 JavaScript 中稍微延迟一个循环内的函数,它应该每 500 毫秒调用一次:

function myFunc(num) {
    return num++;
}

var theNum = 0;

while (theNum != 10) {
    theNum = setTimeout(myFunc(theNum), 500);
}
console.log("All done");

但是,All done 永远不会被记录。

  1. 您正在立即调用函数。您需要将函数 reference 传递给 setTimeout

  2. 并且由于该问题,您还创建了一个无限循环。

  3. 即使您更正了这个问题,“全部完成”仍会在任何超时完成之前先被记录下来。

因此您需要重新考虑该方法。将超时放在函数中,如果 theNum 小于 10,则使用递增的数字再次调用该函数(setTimeout 允许您在延迟后传入参数)。当计数达到 10 时记录“全部完成”。

function myFunc(num) {
  return `Number: ${num}`;
}

function loop(theNum = 0) {
  if (theNum < 10) {
    console.log(myFunc(theNum));
    setTimeout(loop, 500, ++theNum);
  } else {
    console.log("All done");
  }
}

loop();