-
-
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.
This file contains hidden or 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
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