I have a producer-consumer design in javascript, where the producer is pulling some JSON data over ajax. The consumers each register interest in the data with a custom callback function, and then each gets a callback triggered after a slight delay when the data is available (or if the load fails).
My current function for actually triggering the callbacks looks like this:
// Function to iterate through all registered callbacks
this._processCallbacks = function() {
var self = this;
for (var callback of this.callbacks) {
setTimeout(function(){ callback(self.data != null) }, 2000);
}
}
... but with this the last callback in the list is called N times, rather than each callback being called once.
If I remove the setTimeout
and just call synchronously it works fine ...
// Function to iterate through all registered callbacks
this._processCallbacks = function() {
var self = this;
for (var callback of this.callbacks) {
callback(self.data != null);
}
}
... so I assume I'm missing some subtlety of closure scope and timeouts. Any help appreciated - I'm not sure what I've missed (the only scope issue I was aware of was the issues around this
being modified).