diegodacal diegodacal -3 years ago 137
Javascript Question

Array index not working in for loop

I have absolutely no idea of whats happening. But when I try to iterate in this, using [i] on line 12, it doesn´t work and I get the span I want to write in totally blank. But, without changing anything else, only switching [i] to [0] on line 12, for example, I get my span written as expected!

Any ideas?

$(function() {
var listaCoisas = [
"disruptiva",
"matadora",
"feroz",
"tradicional"
];

var i;
for (i=0; i<listaCoisas.length; i++){
setTimeout(function(){
$('#word-attribute').empty().append(listaCoisas[3]);
},1000);
}
});

Answer Source

As you want each iteration to be 1 second after the previous, you need to change the setTimeout delay - using forEach

listaCoisas.forEach(function(entry, i){ 
    setTimeout(function(){ 
        $('#word-attribute').empty().append(entry); 
    },(i+1) * 1000); 
});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download