Skip to content

Instantly share code, notes, and snippets.

@v1ct0rv
Created March 13, 2014 05:30
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 v1ct0rv/f9bcae83d883bfb0296e to your computer and use it in GitHub Desktop.
Save v1ct0rv/f9bcae83d883bfb0296e to your computer and use it in GitHub Desktop.
Puzzle test

Put both files in the same directory and run 'node app'

var throttler = require('./throttler');
var asyncFunction = function(x, callback) {
return setTimeout((function() {
return callback(x * x);
}), 1000);
};
throttledFunction = throttler(asyncFunction, 3);
for (var i = 0; i < 100; i++) {
// Call throttledFunction
throttledFunction(i, function(y) {
console.log(y);
});
};
module.exports = function(asyncFunction, concurrencyLevel) {
var queue = [];
var running = 0;
var throttledFunction = function(x, callback) {
queue.push(function(done) {
asyncFunction(x, function(result){
// call fist done function because A resource is "in use" between the time
// the asynchronous function starts and the time it calls its callback with the result.
done();
callback(result);
});
});
};
// Run a function each 1ms (can be changed) to check the data in the queue.
var intervalID = setInterval(function() {
if (queue.length > 0 && running < concurrencyLevel) {
running++;
// dequeue and run the function.
var func = queue.shift();
func(function(){
running--;
});
};
}, 1);
return throttledFunction;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment