Just for context, what I have is a relatively high throughput websocket implementation. Messages are sent through an open websocket from server to server. However, when a connection is lost we need to queue messages until the connection is regained. At this point we don't care much for persistence, in that if the server were to crash we don't need to have a backup of the messages. We also don't care much for the order of the messages.
So what I have so far is similar to the following:
function sendPayload( payload ) {
var self = this;
if ( self._state !== states.connected ) {
// Queue until connected
setImmediate( sendPayload.bind( self, payload ) );
}
else {
self._wsClient.send( payload );
}
}
The above has caused some odd looks from peers so I wanted to run it by you all. I was hoping to avoid managing an actual queue (populating an array etc.) and figured this was a quick and easy way to keep messages on hold until the connection is established, and quickly send them once it has.
Some have suggested that using setTimeout(fn, 0) might be better but didn't really provide much detail as to why. In this sense I don't think there would be much relevant difference between them, given my requirements.
Is one of the above a better approach than the other, or should I be doing this entirely differently?