Yannick Mackor Yannick Mackor - 4 years ago 117
Javascript Question

Why doesn't the count up clock work?

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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download