title: Stop my React for loop from executing when component umounts
body: <p>I'm trying to stop a for loop from running when my component unmounts.</p>
  <p>The isolated example is as follows:</p>
  <p>My widget is a printer. When the printer is open, it prints &quot;hello world&quot; 1M times. And when the printer is closed it stops.</p>
  <p>My problem is that I can't get the printer to stop printing when its closed. When I close the printer, the for loop continues to run. I thought that I would be able to stop the printer from printing by updating <code>isOpen</code>. But when I close the printer, the isOpen variable, in the scope of the for loop seems to be stuck on <code>true</code>. How can I interrupt the for loop from running when this component dismounts?</p>
  <p>I seem to have some fundamental misunderstanding about how react state and functions work together.</p>
  <pre class="lang-js prettyprint-override"><code>const SelectionPrinter = (props: {isOpen: boolean}): JSX.Element =&gt; {
  
  
      useEffect(() =&gt; {
          runThePrinter()
      }, [props.isOpen])
  
      const runThePrinter = (isOpen: boolean) =&gt; {
          for (let x = 0; x &lt; 1000000; x++) {
              if (isOpen) {
                  print(isOpen)
              }  
          }
      }
  
      const print = (isOpen: boolean) =&gt; {
          setTimeout(() =&gt; {
              if (isOpen) {
                  console.log(&quot;hello world&quot;)
              } else {
                  console.log(&quot;goodbye&quot;)
              }
          })
      }
  
      return (&lt;div&gt; Printer &lt;/div&gt;)
  export default SelectionPrinter
  </code></pre>