-2
for(i=0;i<10;i++){
    setTimeout(function(){
        document.write(i);
    },(i*1000));
}

This is my code, it works except for the counting part. Every second it writes 10. Can anyone tell me why?

Rafael
  • 18,349
  • 5
  • 58
  • 67

1 Answers1

2

This is a known issue. When you are iterating like this value of i changes, before timeout function is executed, you need to copy i value for each execution.

The simplest solution is to pass it to a separate method, like so:

for(i=0;i<10;i++){
   addToDocument(i);
}

function addToDocument(i){
 setTimeout(function(){
        document.write(i);
    },(i*1000));
}

The problem with javascript, unlike java is that it does not treat i as final inside clusure, that is why you need to copy it's value.

Community
  • 1
  • 1
Beri
  • 11,470
  • 4
  • 35
  • 57