0

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.

aspirinemaga
  • 3,753
  • 10
  • 52
  • 95
  • Whats the matter for that? – Marc Sep 01 '22 at 13:47
  • If I get like 5 messages at once, it fires 5 functions at the same time, that's not what I want – aspirinemaga Sep 01 '22 at 13:48
  • Do every client trigger the same function? And you want the function just to run once every x seconds? If so, sounds like classical "debouncing" Simple code snippet can be found here: https://www.freecodecamp.org/news/javascript-debounce-example/ – Marc Sep 01 '22 at 13:50
  • 1
    Many debouncers only trigger their action when the stream of input stops. If that won't be the case, simply storing the timestamp of the last handled message & ignoring everything where `Date.now() <= timestamp + 2000` would probably do. – RickN Sep 01 '22 at 13:53
  • As was yours—debouncing might work just fine, it all depends on what's happening in OP's application. – RickN Sep 01 '22 at 14:04
  • I'm not quite sure how to make debounce with my code. I've updated a question. It's like it ignores a debounce and runs it 5 times at the same time – aspirinemaga Sep 01 '22 at 14:07

1 Answers1

1

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))
})
IT goldman
  • 14,885
  • 2
  • 14
  • 28