如何在NodeJS中创建无限循环

btqmn9zl  于 2022-12-12  发布在  Node.js
关注(0)|答案(5)|浏览(129)

我在JS上看到了一堆关于无限循环的答案,我想这对我的代码会有帮助,但它似乎没有正常工作。我有:

var i = 0

while (true) {
  setTimeout(() => {
    i ++
    console.log('Infinite Loop Test n:', i);
  }, 2000)
}

目标是在无限循环中每2秒获取一次日志,但我似乎无法获得任何信息...我哪里错了?
提前感谢您一如既往的帮助!

dbf7pr2w

dbf7pr2w1#

为什么要使用while循环呢?要么使用setInterval,要么(更好)创建一个函数,在超时后再次调用它自己:

function logEvery2Seconds(i) {
    setTimeout(() => {
        console.log('Infinite Loop Test n:', i);
        logEvery2Seconds(++i);
    }, 2000)
}

logEvery2Seconds(0);

let i = 0;
setInterval(() => {
    console.log('Infinite Loop Test interval n:', i++);
}, 2000)
kwvwclae

kwvwclae2#

您要查找的函数是setInterval,其用法如下:setInterval(callback, millis)

6ie5vjzr

6ie5vjzr3#

下面是TypeScript实现和用法的示例:

interface ILoopContext<T> {
  data: T;
  state: "RUNNING" | "PAUSED";
}

function loop<T>(
  interval: number,
  context: ILoopContext<T>,
  func: (options: { data: T; start: () => void; stop: () => void }) => void
) {
  const stop = () => context.state = "PAUSED";
  const start = () => context.state = "RUNNING";

  setTimeout(() => {
    if (context.state === "RUNNING") {
      func({ data: context.data, start, stop });
    }

    loop(interval, context, func);
  }, interval);

  return { start, stop };
}

loop(1000, { state: "RUNNING", data: { counter: 0 } }, (options) => {
  const { stop, data } = options;
  data.counter += 1;
  console.log(data.counter);
  if (data.counter == 10) {
    stop();
  }
});
cotxawn7

cotxawn74#

var x = true;
while(x){
   console.log("In loop")
}
mutmk8jj

mutmk8jj5#

请使用PromisesetTimeout

const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
let i = 0;
while(true){
    await sleep(3000);//3000ms
    i++;
    console.log('Infinite Loop Test n:', i);
}

相关问题