How do I set ‘i’ in the function below to be incremental inside the setInterval rather than reading the final value of ‘i’ ?
window.onload= function(){
var res = ['a','b','c']
for(i=0;i<res.length;i++){
document.body.innerHTML += "<li id='L"+i+"' style='display:none;'>"+res[i]+"</li>";
setTimeout(function(){
document.body.innerHTML += 'L'+i+'<br/>';
document.getElementById('L'+i).style.display = 'block'
},1000+i*50);
}
}
outputs:
L3
L3
L3
For loops (or any blocks for that matter) don’t provide a new scope for free like in other languages, you must either use an inline closure or use functional iteration with
.forEachwhere you get the inline closure as a “side effect”:If required, use the shim here for older browser support:
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/forEach