Skip to content

Instantly share code, notes, and snippets.

@fripSide
Last active December 18, 2015 02:39
Show Gist options
  • Save fripSide/5712703 to your computer and use it in GitHub Desktop.
Save fripSide/5712703 to your computer and use it in GitHub Desktop.
When the code is running asynchronously, the for-loop will end before the value 'fi' is printed.As a result of closure,inner function 'testClosure' has access to variables fi of the outer function .But the value of 'fi' will not be set to 0 any more(the first for-loop is finished). So the output of the asynchronous code is 1-2-3-4-5-6.
var events = require('events');
var util = require('util');
//http://rainsilence.iteye.com/blog/1534720
var sleep = function(time) {
var startTime = new Date().getTime();
while(new Date().getTime() < startTime + time);
};
//non-blcoking
var tevent = function() {
}
util.inherits(tevent,events.EventEmitter);
tevent.prototype.doSomething = function(){
var eve = this;
setTimeout(function(){
eve.emit('end');
},200);
}
tevent.prototype.Start = function(){
this.emit('start');
}
function testClosure(callback) {
var t = new tevent;
t.on('start',function(){
t.doSomething();
}).on('end',function(){
if (callback) {
callback();
};
});
t.Start();
};
//out: 123 123
(function(){
console.log('Sync:');
for(var i = 0; i < 2; ++i) {
var fi = 0;
for(var j = 0; j < 3; ++j) {
sleep(200);
++fi;
console.log(fi);
}
}
})();
//out: 123 456
(function(){
console.log('Async:');
for(var i = 0; i < 2; ++i) {
var fi = 0;
for(var j = 0; j < 3; ++j) {
testClosure(function(){
++fi;
console.log(fi);
});
}
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment