0

Well, I have reduced my problem to the following:

I have a node.js server sending responses to my WebSocket client (browser) at an interval of 2s. The client code to receive the response is as follows:

socket.onmessage = function (message) {
    //display message
}        

In most cases, I can receive a response in at least 2s on the client. However, sometimes due to poor network connection or high server load, I can get a burst of responses from the server. For example, instead of one response in 2s, I get 3 responses at once in 6s.

How can I handle the situation at the client so that a delay of at least 2s is preserved?

One option is to queue all the responses in the client and then have a timer that periodically checks the queue. Is there a better way?

Also is the function onmessage thread-safe? That is, does a new response from the server blocks while the code block is being executed?

Kamil
  • 968
  • 1
  • 8
  • 18

1 Answers1

0

There's only one thread running your JavaScript on the browser (unless you're using workers), so it is thread safe.

However, the event loop will be blocked until your onmessage handler returns, and all other messages will be queued in the event queue until they are processed.

You could add the messages to a queue as soon as they arrive, and have an interval running every 2 seconds to pop an item off the queue and process it.

However, once you get a delay, suddenly you have a permanent delay that will never leave and only grow larger? Perhaps you can provide us with more information as to why you need a 2 second interval on the client. It seems like a strange requirement to me

One of the solutions from here may provide a rate limiting queued function call, which you can use to rate limit your UI updates. Make sure to make the rate faster than the server so it can catch up on larger queues.

Community
  • 1
  • 1
Joseph Young
  • 2,758
  • 12
  • 23
  • The client updates the UI for each response from the sever. And it is important that the user gets some a brief delay to see the changes. – Kamil Aug 24 '16 at 19:07
  • I would recommend using a function such as the ones mentioned in http://stackoverflow.com/questions/23072815/throttle-javascript-function-calls-but-with-queuing-dont-discard-calls which allows a function to be queued and rate limited. However, if using this method, make sure to make the delay slightly less than the server so that it can catch up – Joseph Young Aug 24 '16 at 19:36