javascriptnode.jswebsocketrate

Limit incoming messages from websocket server in javascript


I'm connected to a Websocket server which can send me like 1 or 20 message events at the same time.

Question 1
Is there a way to limit the amount of incoming messages per one event ?

For example:

At 16:00:00 - I can get 1 message per event
At 16:00:12 - I can get 5 messages per event
client.on('connect', async (connection) => {
  connection.on('message', async event => {
    console.log(event.length) // <----- length is always undefined
    if (event.type === 'utf8') {
      const data = JSON.parse(event.utf8Data)

      await trigger(data)
    }
  })
})

async function trigger (data) {
  // ... async/await functions
}

If I get more then 1 message per 1 websocket event, for example (5 messages per event), it will call trigger() 5 times at once. That's not an acceptable way.


Solution

  • One option to rate limit your resources is using a "throttle" function. So for example not more than one call per 200ms would look like (not tested):

    // from https://stackoverflow.com/a/59378445/3807365
    function throttle(func, timeFrame) {
      var lastTime = 0;
      return function() {
        var now = Date.now();
        if (now - lastTime >= timeFrame) {
          func();
          lastTime = now;
        }
      };
    }
    
    client.on('connect', async(connection) => {
      connection.on('message', throttle(event => {
        console.log(event.length) // <----- length is always undefined
        if (event.type === 'utf8') {
          const data = JSON.parse(event.utf8Data)
    
          trigger(data)
        }
      }, 200))
    })