I'm looking for a javascript client side lib to handle an ajax or websocket requests queue like this :
Ideally :
I can't find anything like this. Should I build one myself using localstorage, window.navigator.onLine and socket.io for instance or is there already some lib for that purpose ?
Thanks.
The question is probably going to be closed, since asking for a library is usually not welcomed on StackOverflow. However, this is a fun little challenge. (Took me ~15 minutes to complete.)
This is actually not a very big task to handle, barely 50 lines or so. That's probably why you can't find a small library doing this.
function Sender() {
var requests = [],
state = 0; // 0 = closed, 1 = open
ws = new WebSocket();
ws.onopen = function() {
state = 1;
if (requests.length) {
send();
}
};
ws.onerror = function() {
if (ws.readyState !== 1) { // 1 is "OPEN"
close();
}
};
// Let's fill in the requests array if necessary
// IIFE because I don't want to pollute the scope with `req`
(function() {
var req = JSON.parse(localStorage.get('queue'));
if (req.length) {
requests = requests.concat(req);
}
}());
return {
send: function(msg) {
if (state === 0) {
requests.push(msg);
}
else {
send();
}
},
close: function() {
state = 0;
localStorage.set('queue', JSON.stringify(requests));
}
};
function send() {
var done = false;
while (!done) {
if (state === 1) {
ws.send(requests.pop());
if (!requests.length) {
done = true;
}
}
else {
done = true;
}
}
}
}
// Usage example
var sender = Sender();
sender.send('message');
// let's say your "disconnect" button is in a variable
disconnect.addEventListener('click', function() {
sender.close();
}, false);
The server doesn't have to handle anything except normal requests. If you want, you can add a timestamp to the message you send, this way it's quite easy (2 lines or so) to keep track of the time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With