Skip to content

Instantly share code, notes, and snippets.

@shuding
Created January 22, 2016 09:07
Show Gist options
  • Save shuding/6e2065fbf458733dbfec to your computer and use it in GitHub Desktop.
Save shuding/6e2065fbf458733dbfec to your computer and use it in GitHub Desktop.
Tricky delay function with ES6 yield, inspired by co
function run(x, cb) {
var f;
if (this.constructor.constructor == (function*() {}).constructor) {
f = this;
} else {
f = x();
}
var w = f.next();
if (!w.done) {
setTimeout(() => {
run.call(f, x, cb);
}, w.value);
} else {
cb && cb(w.value);
}
}
//=======================
run(function *count() {
console.log(1);
yield 10; // sleep 10ms
console.log(2);
yield 1000; // sleep 1s
console.log(3);
yield 1000; // sleep 1s
return 4;
}, function (res) {
console.log('result = ', res); // finish
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment