Skip to content

Instantly share code, notes, and snippets.

@billywhizz
Created July 11, 2011 15:34
Show Gist options
  • Select an option

  • Save billywhizz/1076103 to your computer and use it in GitHub Desktop.

Select an option

Save billywhizz/1076103 to your computer and use it in GitHub Desktop.
function Adder(cb) {
var _adder = this;
var _complete = false;
var _result = 0;
var _jobs = 0;
_adder.add = function(x,y) {
setTimeout(function() {
_result += (x+y);
_jobs--;
if(_complete && !_jobs) {
cb(_result);
}
},10);
_jobs++;
}
_adder.finish = function() {
_complete = true;
}
_adder.start = function() {
_complete = false;
_result = 0;
_jobs = 0;
}
}
function display(result) {
console.log(result);
}
var a1 = new Adder(display);
a1.start();
a1.add(1,2); // 3
a1.add(2,3); // 5
a1.add(3,4); // 7
// result should be 15
a1.finish();
var a2 = new Adder(display);
a2.start();
a2.add(10,10); // 20
a2.add(20,20); // 40
a2.add(30,30); // 60
// result should be 120
a2.finish();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment