title: Recommended way to redraw an html canvas from inside a loop using setTimeout
body: <p>I have researched a lot, mostly in SO, about <code>setTimeout</code> being "not blocking", and so being not suitable to be used inside a for loop, since the loop keeps going on and one while the function calls keep building up.</p>
  
  <p>I have an HTML file which documents an image processing algorithm, so I want to display the active pixels "walking" in a "human-readable" speed. The implementation I tried and does not work is the following:</p>
  
  <pre><code>&lt;!DOCTYPE html&gt;
  &lt;html lang="en"&gt;
  &lt;head&gt;
  &lt;meta charset="utf-8"&gt;
  &lt;/head&gt;
  
  &lt;body onload="run();"&gt;
  
      &lt;canvas id="Canvas" width=501 height=601&gt;&lt;/canvas&gt;
  
      &lt;script&gt;
  
          function run() {
              reevaluate();
          };
  
          var fixedcenteri;
          var fixedcenterj;
  
  
  
          function reevaluate() {
  
              var altura_imagem = 50;
              var largura_imagem = 40;
  
              for (var i = 0; i &lt; altura_imagem; i++) {
                  for (var j = 0; j &lt; largura_imagem; j++) {
  
                      fixedcenteri = i;
                      fixedcenterj = j;
  
                      setTimeout(draw, 100);
  
  
                      // if I uncomment this I can see what I want, but...
                      // alert(i+j);
                  };
              };
          };
  
  
          function draw () {
              var elem = document.getElementById('Canvas');
              var cx = elem.getContext('2d');
  
              w = elem.width;
              h = elem.height;
  
              cx.fillStyle = "white";
              cx.fillRect(0,0,w,h);
  
              cx.fillStyle = 'blue';
              cx.fillRect(fixedcenteri, fixedcenterj, 10, 10);
          }
  
      &lt;/script&gt;
  &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>