Skip to content

Instantly share code, notes, and snippets.

@fillano
Created March 30, 2014 03:03
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fillano/9866779 to your computer and use it in GitHub Desktop.
Save fillano/9866779 to your computer and use it in GitHub Desktop.
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