I have a function that writes some text in the console after 3 seconds in the for a loop. Here it is:
const arr = [0, 0, 0, 0];
for (var i = 0; i < arr.length; i++) {
setTimeout(function() {
console.log("Index: " + i + ", element: " + arr[i]);
}, 3000);
}
The problem is that the output in the console is not correct. It is as follows:
Index: 4, element: undefined
Index: 4, element: undefined
Index: 4, element: undefined
Index: 4, element: undefined
But I expect it to be like this:
Index: 0, element: undefined
Index: 1, element: undefined
Index: 2, element: undefined
Index: 3, element: undefined
Please, tell me what Iām doing wrong.