Two ways you can get around this. This happens because the scope of variable defined with var
is its current execution context. Making i
a global variable that will be reused in your loop.
Use the let keyword:
[let] works as intended because the instances of the (anonymous) inner function [of the for loop] refer to different instances of the variable i
This is because:
Variables declared by let have as their scope the block in which they are defined, as well as in any contained sub-blocks
for( let i = 0; i < step.length; i++ ){
setTimeout( function( ){
insideJMove.doMove( i );
} , 1000 );
}
or Immediately Invoked Function Expression
This creates a new execution context where the value of i
stays as whatever it was when the function expression was executed.
for( var i = 0; i < step.length; i++ ){
(function(i){
setTimeout( function( ){
insideJMove.doMove( i );
} , 1000 );
})(i);
}