Last active
February 2, 2017 04:31
-
-
Save brigand/56641f060ea13f56eeedcfb825be6fd7 to your computer and use it in GitHub Desktop.
This allows doing expensive computation, periodically yielding to the event loop, while keeping synchronous syntax
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 nonBlocking(generator) { | |
return (...args) => { | |
var callback = args[args.length - 1]; | |
var iter = generator(...args); | |
function next() { | |
try { | |
var res = iter.next(); | |
} | |
catch (e) { | |
callback(e); | |
return; | |
} | |
if (!res.done) { | |
setTimeout(next, 5); | |
} | |
else { | |
callback(null, res.return); | |
} | |
} | |
next(); | |
} | |
} | |
var f = nonBlocking(function*(until) { | |
var n = 0; | |
for (var i=0; i<until; i++) { | |
if (i % 1000 === 0) { | |
console.log(i); | |
yield; | |
} | |
n += i; | |
} | |
return n; | |
}); | |
f(1e5, (err, res) => { | |
console.log('res: ' + res); | |
clearInterval(interval); | |
}); | |
var interval = setInterval(() => { | |
console.log('interval'); | |
}, 100); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment