使用socket.io和nodejs向连接的客户端发送连续更新

时间:2021-09-15 16:27:53

Can anyone tell me how to send continuous updates to connected clients every second using nodejs and socket.io?

谁能告诉我如何使用nodejs和socket.io每秒向连接的客户端发送连续更新?

NOTE: I don't want to use the setInterval() function as it is unfit for my current scenario.

注意:我不想使用setInterval()函数,因为它不适合我当前的场景。

1 个解决方案

#1


1  

You can do this with setTimeout in a function that references itself in the setTimeout. Basically the same result as doing setInterval but will always wait for the function to finish (assuming synchronous code) before running the timeout function again.

您可以使用setTimeout在setTimeout中引用自身的函数中执行此操作。基本上与执行setInterval的结果相同,但在再次运行超时函数之前总是等待函数完成(假设同步代码)。

function thingToRepeat() {
  let shouldCancel = false;
  // send messages, do stuff, 
  // set shouldCancel to true to stop looping if needed

  if (!shouldCancel) {
    setTimeout(thingToRepeat, 1000);
  }
}

#1


1  

You can do this with setTimeout in a function that references itself in the setTimeout. Basically the same result as doing setInterval but will always wait for the function to finish (assuming synchronous code) before running the timeout function again.

您可以使用setTimeout在setTimeout中引用自身的函数中执行此操作。基本上与执行setInterval的结果相同,但在再次运行超时函数之前总是等待函数完成(假设同步代码)。

function thingToRepeat() {
  let shouldCancel = false;
  // send messages, do stuff, 
  // set shouldCancel to true to stop looping if needed

  if (!shouldCancel) {
    setTimeout(thingToRepeat, 1000);
  }
}