Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Abusing JavaScript generators and yield one can create task schedulers that essentially allow to write code that waits without blocking for asynchronous events. Originally and The difference between the two versions…
function OnYieldWaitForEvent(cor, target, name, phase) {
var self = arguments.callee;
target.addEventListener(name, function(evt) {
// We need to unregister the listener to save resources
// and to avoid getting called if the event occurs again
evt.currentTarget.removeEventListener(name, self, phase);
// Resume the waiting function;
}, phase);
function ExecWithOnYield(func) {
var generator = new func;;
// There is no arguments.generator or `this generator` yet
// and arguments.callee refers to the Function object, so
// we have to pass a self-reference to the instance.
function test() {
var self = yield;
// Create a new <img> object
var img1 = new Image(315, 48);
OnYieldWaitForEvent(self, img1, 'load', false);
img1.src = '';
yield; // wait for img1 'load'
// ... load more images here ...
// Now draw them all on a <canvas>
// Signal we are done so the event handler does not have to
// catch an exception that would otherwise be generated.
yield 'done';
function OnYieldWaitForEvent(target, name, useCapture) {
return function(resume) {
var listener;
listener = function(){
target.removeEventListener(name, listener, useCapture);
target.addEventListener(name, listener, useCapture);
function ExecWithOnYield(func) {
var generator = new func;
var ExecOneStep;
ExecOneStep = function(){
try {
var wrapped =;
// TODO: what if `wrapped` throws `StopIteration`?
catch (e) {
if (e instanceof StopIteration) {
} else {
console.log("other exception");
function test() {
var img1 = new Image(315, 48);
img1.src = '';
yield OnYieldWaitForEvent(img1, 'load', false);
console.log("img1 has loaded when we get here");

This comment has been minimized.

Copy link

hollowdoor commented Sep 5, 2015

With all the addEventListener, and removeEventListener would this cause issues for a ton of events? Like if you were to do mouse move tracking in a loop?

Using it for clicks would probably be ok.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.