1

below is my code
and it is displaying 6000 6000 6000 6000 6000 after 1 sec each time.
But i want to display 1000 2000 3000 4000 5000 using setTimeout()
fiddle: https://jsfiddle.net/himavicii/jg2uvu1j/

var i=0;
for(i=1000;i<6000;i+=1000)
{
    setTimeout(function(){v(i)},i);
}
function v(h)
{
    document.write(h+' ');
}
Tom
  • 83
  • 9

2 Answers2

3

This happens because all of the timeouts are referring to the same i variable. Wrap the timeout in a closure:

for(i=1000;i<6000;i+=1000)
{
    (function(i){
        setTimeout(function(){v(i)},i);
    })(i);
}

This passes i as an argument to an anonymous function, and functions create a new scope, so the variable is protected.

MrCode
  • 63,975
  • 10
  • 90
  • 112
2
var i=0;
for(i=1000;i<6000;i+=1000)
{
    timeoutFun(i);
}

function timeoutFun(t){
  setTimeout(function(){
       v(t);
    },t);
}
function v(h)
{
    document.write(h+' ');
}

https://jsfiddle.net/shadiq_aust/s4078702/

Md Rahman
  • 1,812
  • 1
  • 14
  • 15