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?
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?
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.