Pausing a generator function


First time here…

I wanted to be able to pause a generator function, so I started with @mbostock/pause-a-generator, and adapted it to be a generator function instead of a generator:

The slightly wonky thing about this is the need to manually bind this whenever I use my pausable generator function. Does this seem reasonable, or would you recommend a different approach?

Thanks for any advice!

You can do this with a class, as below, though I’m not sure the syntax is any better.
With static variables in JS classes (now in stage 3) it should be possible to do something like Counter.go(paused)


The bind is not necessary, as this merely provides the initialization value:

function* counter(paused, i = 0) {
  if (paused) return yield i;
  while (true) yield ++i;
counter(paused, this)

this will always contain a cell’s previous value (or undefined for the first run).

Whenever counter is rerun or the paused view produces a new value, the counter(paused, this) cell is rerun with the new values from its dependencies, and this containing the previous value.


Thank you @dhowe and @mootari!

@dhowe, I do like the thought of using the class mechanism to take care of binding this, but @mootari, you have opened my eyes to the fact that I was focusing on the wrong aspect of the original example. From the point of view of the generator function, this is really just state that is being passed in, and while the cell that is calling the function can use Observable’s magic this to maintain the state across invocations, the function itself can simply take it as a regular parameter. @mootari’s suggestion strikes me as the clean and elegant way to go here. I’ve updated the notebook based on this approach.