Skip to content

Instantly share code, notes, and snippets.

@tanduong
Created September 16, 2016 15:18
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 tanduong/ea29c25f5d1cc619cd0331c10abaea7c to your computer and use it in GitHub Desktop.
Save tanduong/ea29c25f5d1cc619cd0331c10abaea7c to your computer and use it in GitHub Desktop.
DebounceRequestQueue
class DebounceRequestQueue {
constructor(queueLength = 6) {
this.queueLength = queueLength;
this.queue = [];
}
request(url) {
return new Promise((resolve, reject) => {
let req = new XMLHttpRequest();
req.open('GET', url);
req.onload = function () {
if (req.status === 200) {
resolve(req.response);
} else {
reject(Error(req.statusText));
}
};
req.onerror = function () {
reject(Error('Network Error'));
};
this.queue.push({req, resolve, reject});
if (this.queue.length > this.queueLength) {
let oldestOutstandingRequest = this.queue.shift();
oldestOutstandingRequest.req.abort();
oldestOutstandingRequest.reject(Error('Markers data call took too long; cancelling'));
}
req.send();
});
}
}
let debounceRequestQueue = new DebounceRequestQueue();
for(let i = 0; i < 20; i++) {
debounceRequestQueue.request("https://api.soundcloud.com/tracks/197355235\?client_id\=978b6cc3cb0ba473f75da8bf6d3d0990")
.then(r => document.write(`${i},`))
.catch(e => document.write(e));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment