Skip to content

Instantly share code, notes, and snippets.

@programus
Forked from Terrance/AjaxQueue.js
Last active October 8, 2021 07:40
Show Gist options
  • Save programus/2267d28e6e34c3a368d7520fbd878e39 to your computer and use it in GitHub Desktop.
Save programus/2267d28e6e34c3a368d7520fbd878e39 to your computer and use it in GitHub Desktop.
Limit concurrent jQuery ajax requests to at most 6 at a time, and queue the rest.
const ajaxPool = {
queue: [],
reqCount: 0,
activeCount: 0,
maxCount: parseInt(searchParams.get('ajaxLimit')) || 6,
add(obj) {
this.reqCount++
const originalSuccess = obj.success
const originalError = obj.error
const callback = () => {
this.reqCount--
if (this.activeCount <= this.maxCount && this.queue.length > 0) {
$.ajax(this.queue.shift())
} else {
this.activeCount--
}
}
obj.success = (resp, xhr, status) => {
callback()
if (originalSuccess) {
originalSuccess(resp, xhr, status)
}
}
obj.error = (xhr, status, error) => {
callback()
if (originalError) {
originalError(xhr, status, error)
}
}
if (this.activeCount < this.maxCount) {
this.activeCount++
$.ajax(obj)
} else {
this.queue.push(obj)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment