Created
January 22, 2016 09:07
-
-
Save shuding/6e2065fbf458733dbfec to your computer and use it in GitHub Desktop.
Tricky delay function with ES6 yield, inspired by co
This file contains 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
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