title: JS Constantly updating CSS background colors in a grid - closure?
body: <p>I have a grid of boxes (3x2) that I'd like to update in a loop given a large array of rgb values representing changing colors over time. An example of one element of the array looks like this:</p>
  
  <p>[[99.58221354166666, 99.20004050925925, 100.86330150462963], [59.431727430555554, 58.59181712962963, 61.26002314814815], [59.824817708333335, 58.83816550925926, 61.85647280092593], [93.02857349537037, 95.04584201388889, 92.13913194444444], [48.46075810185185, 50.74021701388889, 46.878373842592595], [84.57517939814815, 173.51900462962962, 62.35618923611111]]</p>
  
  <p>The code below handles the rgb values and everything perfectly. Each element of the array corresponds to a "box" in the 3x2 grid. Unfortunately, my loop seems to have a closure problem and I can't figure it out. It only updates the grid's colors on the last iteration. So I rewrote it to store a list of functions and then call those, but I can't tell if it's just executing so fast I can't see it or if it's actually failing. If I add a sleep in, the script will hang and wherever it hangs it'll update for that one moment until I click continue script. After which it'll show me the last update (so I've gone from seeing on the last update to seeing two with a script apparently hanging).</p>
  
  <pre><code>c1 = $("#cell1");
  c2 = $("#cell2");
  c3 = $("#cell3");
  c4 = $("#cell4");
  c5 = $("#cell5");
  c6 = $("#cell6");
  var cells = [c1, c2, c3, c4, c5, c6];
  
  $(document).ready(function() {
      $.each(test, function(iGrid, grid) {
          var ary_rgb = [];
          var property = "background";
          var updates = [];
          $.each(grid, function (iBox, box) {
              var r = Math.floor(box[0]).toString();
              var g = Math.floor(box[1]).toString();
              var b = Math.floor(box[2]).toString();
              var rgb = 'rgb(' + r + ',' + g + ',' + b + ')';
              updates[iBox] = function () { return cells[iBox].css(property, rgb); };
          });
  
          for (var i=0; i&lt;updates.length;i++) {
              updates[i]();
          }
      });
  });
  </code></pre>
  
  <p>I did spend several hours trying to get this working and reading SO and other sites on closures but I just can't see what I'm doing wrong. I can post the rest of the html if needed.</p>