title: How to set and clean interval by toggle function in react with hooks?
body: <p>I'm trying to build a timer witch is triggered by one button with function <em>handleToggle</em>, which looks like:</p>
  
  <pre><code>const handleToggle = () =&gt; {
      let timer = () =&gt; setInterval(() =&gt; {
        dispatch({ type: "COUNT", payload: Date.now() - startTime });
      }, 100);
      const startTime = Date.now() - AppState.runningTime;
      if (AppState.countingStarted) {
        dispatch({
          type: "COUNTING_STARTED",
          payload: false
        });
        clearInterval(timer());
      } else {
        timer()
        dispatch({ type: "COUNTING_STARTED", payload: true });
      }
    };
  </code></pre>
  
  <p><em>COUNTING_STARTED</em> is a dispatch function which toggles <em>AppState.countingStarted</em>.</p>
  
  <p>I'm struggling with stopping a timer, how to clear that timer-Interval?
  I tried:</p>
  
  <pre><code>const handleToggle = () =&gt; {
      let timer;
      if (AppState.countingStarted) {
        dispatch({
          type: "COUNTING_STARTED",
          payload: false
        });
        clearInterval(timer);
      } else {
        timer = setInterval(() =&gt; {
          dispatch({ type: "COUNT", payload: Date.now() - startTime });
        }, 100);
        const startTime = Date.now() - AppState.runningTime;
        dispatch({ type: "COUNTING_STARTED", payload: true });
      }
    };
  </code></pre>
  
  <p>but there is no difference...</p>