-
-
Save thomaswilburn/7503697 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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