Put both files in the same directory and run 'node app'
Created
March 13, 2014 05:30
-
-
Save v1ct0rv/f9bcae83d883bfb0296e to your computer and use it in GitHub Desktop.
Puzzle test
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
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); | |
}); | |
}; |
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
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