【问题标题】:How to execute a function periodically in NodeJS [duplicate]如何在NodeJS中定期执行功能[重复]
【发布时间】:2021-12-30 07:39:23
【问题描述】:

我已经尝试过setInterval(),它看起来很完美,但问题是它不会立即启动第一个调用并等待 X 秒然后给出所需的值,是否有其他方法或者我应该运行它无限循环并在其中放入类似sleep 的功能?

【问题讨论】:

标签: javascript node.js


【解决方案1】:

如果您的问题只是第一次没有调用,那么没关系

function doThis(){
console.log("hello");
}
const time = 1000;
doThis(); // Calls for the first time
setInterval(doThis(),time); // Now it starts the samething.


//There is another option also for same thing:

setInterval(function doThis() {
  console.log('hello');
  return doThis();
}(), time);


但不推荐function takes longer than delayed time 有关此声明的更多信息: https://dev.to/akanksha_9560/why-not-to-use-setinterval--2na9

https://chrisblackwell.me/setinterval-is-bad/

function doThis() {
console.log("hellow");

  setTimeout(doThis, 1500);
}
doThis();

setInterval 发生的问题不会在这里发生,因为这只会安排下一次迭代,而不是所有未来的迭代。

对于setInterval 对于setTimeout

【讨论】:

  • 如果 func() 中的第一行是下一次迭代的 settimeout 调用,它们是不是相同或接近?
猜你喜欢
  • 1970-01-01
  • 2018-11-07
  • 2017-10-13
  • 1970-01-01
  • 2016-04-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多