Here is my code:
function addRcd2(timeOut){
for(var c=0; c less 5; c++){
var rcdi = "rcd_"+c+"";
setTimeout(function(){
$('.tbl1 tbody').append(rcdi);
},timeOut*c);
}
}
The output of this code is a table which rows have the same text rcd_5.
My goal is to have a table rows have different records rcd_1, …, rcd_5.
Any ideas?
Typical creating a function in a loop problem. All closures you pass to
setTimeouthave a reference to the samercdivariable. Defining the variable inside the loop is the same as defining it outside:which makes it a bit more apparent that you only deal with one variable here.
You have to introduce a new scope, which in JavaScript can only be achieved through functions:
As you can see in other answers, you can also use immediate functions. Use what you find more readable.