Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@thomaswilburn
Forked from davethegr8/BatChannel.js
Last active December 28, 2015 12:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thomaswilburn/7503697 to your computer and use it in GitHub Desktop.
Save thomaswilburn/7503697 to your computer and use it in GitHub Desktop.
//taking a crack at it
//totally untested, probably doesn't work
var BatChannel = function(endpoint, interval) {
this.endpoint = endpoint;
this.pending = [];
this.interval = interval || 30000;
this.tick();
};
BatChannel.prototype = {
request: function(url, data, callback) {
this.pending.push({
url: url,
data: data,
callback: callback
})
},
send: function() {
if (!this.pending.length) return;
//copy the pending items and clear the queue for new requests
var messages = this.pending.slice();
this.pending = [];
//send the request. Server is responsible for returning a matching array
//we don't fret the callbacks, because JSON will skip them
var data = JSON.stringify(messages);
var xhr = new XMLHttpRequest();
xhr.open("POST", this.endpoint);
//my xhr is a little rusty, but you know what I mean
xhr.onload = xhr.onerror = function process() {
var isError = xhr.readystate = 4;
var response = JSON.parse(xhr.responseText);
for (var i = 0; i < response.length; i++) {
messages[i].callback(isError ? "XHR failed" : response[i].error, response[i].data);
}
};
xhr.send(data);
},
tick: function() {
this.send();
setTimeout(this.tick.bind(this), this.interval);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment