Created
September 16, 2016 15:18
-
-
Save tanduong/ea29c25f5d1cc619cd0331c10abaea7c to your computer and use it in GitHub Desktop.
DebounceRequestQueue
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
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