简体   繁体   English

如何在 Set 元素上的 for of 或 forEach 循环的每次迭代之间添加延迟?

[英]How do I add a delay between each iteration of a for of or forEach loop over Set elements?

I have a function like shown below where websocketServer.clients basically contains a Set of websocket objects.我有一个 function 如下所示,其中 websocketServer.clients 基本上包含一组 websocket 对象。 The setInterval causes my server to get spikes and I would like to basically terminate inactive clients one by one with a small delay in between in a more uniform manner. setInterval 导致我的服务器出现峰值,我想基本上以更统一的方式一个接一个地终止不活动的客户端,中间有一个小的延迟。 Both forEach and for of loops run instantaneously, how do I add a delay between them to replicate the same functionality without using a setInterval? forEach 和 for of 循环都是即时运行的,我如何在它们之间添加延迟以在不使用 setInterval 的情况下复制相同的功能?

export function terminateIdleConnections() {
  const interval = setInterval(function ping() {
    console.log('entry', new Date());
    websocketServer.clients.forEach(function each(ws) {
      // @ts-ignore
      if (ws.isAlive === false) {
        console.log('terminating connection', new Date());
        return ws.terminate();
      } else {
        console.log('pinging connection', new Date());
        // @ts-ignore
        ws.isAlive = false;
        ws.ping();
      }
    });
  }, WEBSOCKET_CHECK_IDLE_CONNECTION_FREQUENCY);

  websocketServer.on('close', function close() {
    console.log('terminating INTERVAL', new Date());
    clearInterval(interval);
  });
}

I suppose that's a weird approach, but what if you try to implement this with setTimeout ?我想这是一种奇怪的方法,但是如果您尝试使用setTimeout来实现它呢? You'd need to initiate another setTimeout with each function call, so the next function activity is rescheduled.您需要在每次 function 调用时启动另一个setTimeout ,以便重新安排下一个 function 活动。

Unluckily I have no setup available to try this approach.不幸的是,我没有可用的设置来尝试这种方法。

setInterval and setTimeout are the only JavaScript approaches I know to delay code execution. setIntervalsetTimeout是我所知道的唯一延迟代码执行的 JavaScript 方法。 Afaik every alternative implementation runs back to these functions, or burns cpu time by looping until a certain date/time is reached. Afaik 每个替代实现都会返回到这些函数,或者通过循环直到达到某个日期/时间来消耗 CPU 时间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM