我正在尝试教自己一些JavaScript,并同时尝试递归。我在下面编写的代码预计将“吸气”到控制台打印10次,两次打印之间有5秒的延迟。但是,当我在Chrome的开发工具中查看控制台时,刷新页面后,所有条目看上去都立即被打印出来。谁能帮助我找到实施中的错误?谢谢!

function breathe(type, counter, limit, duration) {
  if(counter <= limit) {
    setTimeout(console.log(type), duration);
    counter++;

    return breathe(type, counter, limit, duration);
  }

  console.log("Finished!");
}

var breathing = breathe("inhale", 1, 10, 5000);

最佳答案

setTimeout方法需要一个函数引用。这应该工作。

function breathe(type, counter, limit, duration) {
  if(counter <= limit) {
    setTimeout(function(){console.log(type)}, duration);
    counter++;

    return breathe(type, counter, limit, duration);
  }

  console.log("Finished!");
}

var breathing = breathe("inhale", 1, 10, 5000);

10-06 04:25
查看更多