title: Force stop a generator function outside the scope
body: <p>I have a generator function and I want to include the possibility of stopping it on click (or on event trigger generally). I could use a variable that is checked on each iteration and set it to true if I wanna stop, and it works, but not until the current iteration is resolved which makes it useless in case of an infinite loop.</p>
  <p>Here's an example:</p>
  <pre><code>const readline = require('readline');
  readline.emitKeypressEvents(process.stdin);
  
  const script = class {
      constructor(name, textCode){
          this.name = name;
          this.forceStop = false;
          this.generator = null;
  
          try {
              textCode += `if(typeof start !== 'undefined') this.start = start;`
              eval(textCode);
          } catch (error) {
              throw error;
          }
          console.log(&quot;Loaded.&quot;)
      }
      
      async run() {
          try{
              this.generator = this.start();
  
              console.log(&quot;Executing, press Enter to stop..&quot;)
              let s = 1;
              let nextValue;
          
              while (true) {
                  const next = this.generator.next(nextValue);
                  
                  nextValue = await next.value; //Here the generator awaits indefinitely for a promise resolve, but I want the possibility to trigger a stop.
  
                  if (next.done === true || nextValue === false || nextValue == &quot;stop&quot; || this.forceStop) {
                      console.log(&quot;Over.&quot;)
                      break;
                  }
                  s++;
              }
          } catch(e){
              console.log(e.message)
          }
      }
      
      stop(){
          //stop here, i tried using this.generator.return(&quot;stop&quot;) but it doesn't work.
          
          this.forceStop = true;
          //this.forceStop works to stop before the whole generator is over but it doesn't solve the problem of not being able to stop while waiting for a promise.
          console.log(&quot;Stopped.&quot;);
      }
  }
  
  
  
  const code = `
      function* start(){
          yield new Promise(r =&gt; setInterval(()=&gt;{
              console.log(&quot;Generator:&quot;, Math.random())
          }, 1000));
          
          yield console.log(&quot;Generator: script over.&quot;)
      }
  `
  
  const example = new script(&quot;infinite loop&quot;, code)
  
  example.run();
  
  //And i wanna be able to call example.stop() whenever and instantly stop it.
  process.stdin.on('keypress', (str, key) =&gt; {
      if(key.name == &quot;enter&quot;) example.stop()
  });
  </code></pre>