0
for(i = 0; i < 10; i++){
    setTimeOut(function(){
        console.log(i);
    },2000);
}

When I execute this, its printing 10, 10 times instead of 1,2,3....10. How do I fix this

santosh
  • 5
  • 1
  • 6

1 Answers1

0

You need to modify your code like this

function print(i){
    console.log(i);
}

for(i=0;i<10;i++){
    setTimeout(print.bind(null,i),2000);
}
Pramod_Para
  • 671
  • 3
  • 10