title: Simplest slideshow in HTML5 canvas, canvas.context.clearRect not working with setTimeout
body: <p>Here is a code of a very simple slideshow, that should show 4 images in 4 seconds, one image per second. Instead, I get a 4-second delay and then all the images get drawn on top of each other. What am I doing wrong?</p>
  
  <pre><code>&lt;html&gt;
  &lt;head&gt;
  &lt;script langugage="javascript"&gt;
  // 4 images
  var image0 = new Image();
  image0.src = "img/image0.png";
  var image1 = new Image();
  image1.src = "img/image1.png";
  var image0 = new Image();
  image2.src = "img/image2.png";
  var image3 = new Image();
  image3.src = "img/image3.png";
  // array of 4 images
  images = new Array(image0, image1, image2, image3);
  
  // this is the main function
  function draw(){
      myCanvas = document.getElementById('myCanvas');
      ctx = myCanvas.getContext('2d');
      counter=0; // this is the index of the next image to be shown
      for (var i=0;i&lt;images.length;i++){
          setTimeout(draw_next_image, 1000);
          ctx.clearRect(0, 0, myCanvas.width, myCanvas.height)
      }
  }
  // this is the function called after each timeout to draw next image
  function draw_next_image(){
      ctx.drawImage(images[counter], 0, 0);
      counter++;
      if (counter&gt;images.length) {counter=0;}
  }
  
  window.onload = draw;
  &lt;/script&gt;
  &lt;/head&gt;
  &lt;body&gt;
      &lt;canvas id="myCanvas" width="800" height="600"&gt;&lt;/canvas&gt;
  &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p><strong>UPDATE: THE ANSWER IS:</strong></p>
  
  <p>In the code above I mistakingly assumed that <code>getTimeout</code> function is synchronous, i.e. I expected, that upon its call the program execution is going to stop, wait 1000 milliseconds, then call the <code>draw_next_image</code> and only then execute <code>ctx.clearRect</code>. </p>
  
  <p>In reality Javascript doesn't work like that. In fact <code>getTimeout</code> is asynchronous, i.e. <code>getTimeout</code> sets a Timeout and returns almost instantly and the code execution continues, so that <code>ctx.clearRect</code> gets called right away and actually <strong>prior</strong> to <code>draw_next_image</code>. So, by the time Timeout expires and calls <code>draw_next_image</code>, execution of code may reach and arbitrary line of code. In my case all the 4 <code>clearRect</code> are going to be called almost at the same time, long before expiration of Timeouts. Then 1000 milliseconds later, all the 4 timeouts are going to expire almost immediately one after another, and all the 4 images going to be drawn almost at the same time, too, without <code>clearRects</code>, which got executed long before.</p>