1

I know that floating point variables require work arounds when dealing with 0.1, 0.2, 0.3 etc.. but this seems unusual?

for(var i=0;i<10;i=i+1){

  console.log("before timeout" + i/10); //returns 0.1 0.2 0.3 etc

  setTimeout(function(){
    console.log("after timeout" + i/10); //returns 1 1 1 etc
  },1000); 

}
jstleger0
  • 105
  • 1
  • 14
  • 1
    change these to `console.log()` instead of `alert()` so you can see a better history of what order they're being called in, and so you don't spam `alert()`s – DLeh Feb 09 '15 at 19:03
  • You aren't losing decimal points, you are instead not understanding how closures work. – Matt Burland Feb 09 '15 at 19:04

4 Answers4

3

variable "i" always be "10" because of timeout will be called after for loop. so you get always integers because of you devide it to 10

Do this for your own good :)

for(var i=0;i<10;i=i+1){
  console.log("before timeout" + i/10); 

    setTimeout(function(i){
       console.log("after timeout" + i/10); 
     },1000, i);  
 }
Tolgahan Albayrak
  • 3,118
  • 1
  • 25
  • 28
1

You have a closure issue. i will always be 10 in this because the setTimeouts resolve after the loop has completed. You can isolate i at runtime by passing it to an immediately executed function:

for(var i=0;i<10;i=i+1){
  console.log("before timeout" + i/10); 

  (function(i){ 
    setTimeout(function(){
       console.log("after timeout" + i/10); 
     },1000);  
   })(i);
}
Malk
  • 11,855
  • 4
  • 33
  • 32
  • since setTimeout can take parameters why we should isolate it with another function? – Tolgahan Albayrak Feb 09 '15 at 19:12
  • 1
    This is true, but it is specific to setTimeout. There are other places where this closure stuff can bite you, like building dynamic html, where setTimeout is not used. – Malk Feb 09 '15 at 19:20
1

Your timeouts are firing after the for loop has completed... at which point i is already set to 10, so all the alerts are correct, i/10 is 1. You should use closures or similar technique to get what you expect.

for (var i = 0; i < 10; i = i + 1) {

  alert("before timeout" + i / 10); //returns 0.1 0.2 0.3 etc

  setTimeout(
    (function(j) { 
      return function() {
          alert("after timeout" + j / 10); //returns 1 1 1 etc
      }
    })(i)
    );
}
MatthewG
  • 8,583
  • 2
  • 25
  • 27
0

This is because 'i' is always 10 in the second alert. You execute the code into the setTimeOut(function(){....},1000) after i has already reached its max value which is 10 in this case.

Dzhambazov
  • 490
  • 2
  • 11