Created
March 30, 2014 03:03
-
-
Save fillano/9866779 to your computer and use it in GitHub Desktop.
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
co(withYield); | |
withoutYield(); | |
function timeout(sec) { | |
return function(notify) { | |
setTimeout(function() { | |
notify(null, new Date().getTime()); | |
}, sec*1000); | |
}; | |
} | |
function co(gen) { | |
var g = gen(); | |
function next(err, data) { | |
var res; | |
if(err) { | |
return g.throw(err); | |
} else { | |
res = g.next(data); | |
} | |
if(!res.done) { | |
res.value(next) | |
} | |
} | |
next(); | |
} | |
function * withYield() { | |
var a = new Date().getTime(); | |
console.log('[with yield]\tcurrent timestamp: '+a); | |
a = yield timeout(1); | |
console.log('[with yield]\tcurrent timestamp: '+a); | |
a = yield timeout(2); | |
console.log('[with yield]\tcurrent timestamp: '+a); | |
a = yield timeout(1); | |
console.log('[with yield]\tcurrent timestamp: '+a); | |
} | |
function withoutYield() { | |
var a = new Date().getTime(); | |
console.log('[without yield]\tcurrent timestamp: '+a); | |
setTimeout(function() { | |
var a = new Date().getTime(); | |
console.log('[without yield]\tcurrent timestamp: '+a); | |
setTimeout(function() { | |
var a = new Date().getTime(); | |
console.log('[without yield]\tcurrent timestamp: '+a); | |
setTimeout(function() { | |
var a = new Date().getTime(); | |
console.log('[without yield]\tcurrent timestamp: '+a); | |
}, 1000); | |
}, 2000); | |
}, 1000); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment