title: javascript var declaration within loop
body: <pre><code>/*Test scope problem*/
  for(var i=1; i&lt;3; i++){
      //declare variables
      var no = i;
      //verify no
      alert('setting '+no);
  
      //timeout to recheck 
      setTimeout(function(){
          alert('test '+no);
      }, 500);
  }
  </code></pre>
  
  <p>It alerts "setting 1" and "setting 2" as expected, but after the timeout it outputs "test 2" twice - for some reason the variable "no" is not reset after the first loop...</p>
  
  <p>I've found only an "ugly" workaround:</p>
  
  <pre><code>/*Test scope problem*/
  var func=function(no){
      //verify no
      alert('setting '+no);
  
      //timeout to recheck 
      setTimeout(function(){
          alert('test '+no);
      }, 500);
  }
  for(var i=1; i&lt;3; i++){
      func(i);
  }
  </code></pre>
  
  <p>Any ideas on how to workaround this problem in a more direct way? or is this the only way?</p>