I am learning about setTimeout and tried to print an array inside a loop with a delay where after each iteration the value at different indexes change.My original array is [1,2,3,4,5]. I want the output to be something like this:
I understand that closures can be used with setTimeout to preserve the value of the parameter until execution like mentioned in these Stack Overflow questions. How to preserve setTimeout parameter value until execution? and setTimeout in for-loop does not print consecutive values
so it tried this
let a = [1,2,3,4,5];
for(let i=0;i<a.length;i++){
a[i]=7;
dotimeout(a,i)
}
function dotimeout(a,i){
setTimeout(function(){
console.log(a)},i*1000)
}
and
let a = [1,2,3,4,5];
for(let i=0;i<a.length;i++){
a[i] = 7;
(
function(b,j){
setTimeout(()=>{
console.log(b);
},j*1000)
}(a,i)
);
}
but both gave me the same result:
I know that the array manipulation can be done inside the setTimeout callback to achieve the desired result, but that is not what my query is
So my question is: Why the function wrapping the setTimeout( closures, not sure if that is the correct term) doesn't work, and how to preserve the setTimeout parameter until execution with the array manipulation outside the setTimeout.