title: Non blocking solution to a setTimeout() and Performance thoughts
body: <p>I'm performing animation and drawings.
  What i'm trying to achieve is the following:</p>
  
  <p>If the current value is greather than the defined peak value the current value is the new peak value.
  If there isn't any peak values for 800ms, the last current value will be the peak value anyway.</p>
  
  <pre><code>function animate() {
      if (ready){
          setTimeout(function() {
              window.requestAnimationFrame(animate);
              draw();
          }, interval);
      }
  }
  
  function draw(){
      for (i = 0; i &lt; 8; i++) {
          if ((currentValue[i] &gt; peak[i] ) || timeOutTriggered[i]) {
              peak[i] = currentValue[i];  
              clearTimeout(timer[i]);
              timeOutTriggered[i] = false;
              timer[i] = setTimeout(callback.bind(undefined, i), 800);        
          }
      }
      drawPieces();
  }   
  
  function callback(i){    
      timeOutTriggered[i] = true;
  }
  </code></pre>
  
  <p>From what i read around this solution is asynchronous in the sense that the counting is performed in the same thread, so from time to time there will be a timer scheduling counting instruction which will affect my drawing fps.</p>
  
  <p>From the timeline when i load my page i always see an initial lag of 800ms (i haven't test it during a drawing phase since the code is not up yet) even if the code should never be reached (init values of currentValue and peak are "0" and timeOutTriggered is always false).</p>
  
  <p>So my questions are:</p>
  
  <ol>
  <li>Why do i have an initial lag of 800ms</li>
  <li>Should i use n° web worker, one for each element of the array? if so how</li>
  <li>Is there a better implementation? How are problem like this handled generally?</li>
  </ol>
  
  <p>Animation is performed with RequestAnimationFrame btw.</p>
  
  <p>fiddle: <a href="https://jsfiddle.net/1j0cz0m9/1/" rel="nofollow">https://jsfiddle.net/1j0cz0m9/1/</a></p>