Last active
December 31, 2015 21:30
-
-
Save jondcoleman/f62a92e2fe8895c1bf1e to your computer and use it in GitHub Desktop.
Rate Limited API call with function call after all calls finished - by Geoff Storbeck
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
<!DOCTYPE html> | |
<html> | |
<head> | |
<script src="https://code.jquery.com/jquery-2.1.4.js"></script> | |
<meta charset="utf-8"> | |
<title>JS Bin</title> | |
</head> | |
<body> | |
</body> | |
</html> |
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
var posts = [1, 2, 3, 4, 5, '????']; | |
var responses = []; | |
var calls = []; | |
// Rate limit function that builds a queue | |
function rateLimit(perSecondLimit, fn) { | |
var callsInLastSecond = 0; | |
var queue = []; | |
// Process the queue | |
return function limited() { | |
// If we have more calls that our limit, push it into the queue | |
if (callsInLastSecond >= perSecondLimit) { | |
queue.push([this, arguments]); | |
return; | |
} | |
// Increase the number of calls by 1 each time | |
callsInLastSecond++; | |
// Execute each per second and reduce the number of calls we have left | |
setTimeout(function() { | |
callsInLastSecond--; | |
var parms; | |
if (parms >= queue.shift()) { | |
limited.apply(parms[0], parms[1]); | |
} | |
}, 1010); | |
// Bind our callback with the arguments we gave it | |
fn.apply(this, arguments); | |
}; | |
} | |
// Only output when we have the same number of items in the responses array as the posts array | |
function log() { | |
// Comment this to view them as they come in | |
if (responses.length === posts.length) { | |
console.log(responses); | |
} | |
} | |
// Handle error messages | |
function errorHandler(err) { | |
console.error(err); | |
} | |
// Add responses to responses array | |
function addResponse(json) { | |
console.log('!'); | |
responses.push(json); | |
} | |
// Function to create a new AJAX call with an addResponse promise | |
function newCall(item) { | |
$.getJSON('http://jsonplaceholder.typicode.com/comments?postId=' + item) | |
.done(function() { | |
addResponse(item); | |
log(); | |
}) | |
.fail(function() { | |
addResponse('{message: "error"}'); | |
errorHandler('Error calling item: ' + item); | |
log(); | |
}); | |
} | |
// Function to rate limit | |
var limitCalls = rateLimit(10, function(i) { | |
newCall(i); | |
}); | |
// Loop over each post call our rate limited function | |
posts.forEach(limitCalls); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment