I’m running into a weird problem with JavaScript loops and functions. When I create functions inside a loop, they all seem to use the same variable value instead of keeping their own copy.
Here’s what I’m trying to do:
var actions = [];
// creating 3 different functions
for (var x = 0; x < 3; x++) {
// storing them in the array
actions[x] = function() {
// want each to show its own number
console.log("Number is:", x);
};
}
for (var k = 0; k < 3; k++) {
// running each function
actions[k]();
}
But I get this result:
Number is: 3
Number is: 3
Number is: 3
What I actually want is:
Number is: 0
Number is: 1
Number is: 2
This same thing happens with click handlers too:
var elements = document.querySelectorAll("input");
for (var x = 0; x < elements.length; x++) {
elements[x].onclick = function() {
console.log("Clicked button:", x);
};
}
<input type="button" value="First">
<input type="button" value="Second">
<input type="button" value="Third">
And with async stuff like timeouts:
const delay = (time) => new Promise(resolve => setTimeout(resolve, time));
for (var x = 0; x < 3; x++) {
delay(x * 50).then(() => console.log(x));
}
Even happens in different types of loops:
const items = [5,10,15];
const callbacks = [];
for (var index in items){
callbacks.push(() => console.log("at:", index));
}
for (var item of items){
callbacks.push(() => console.log("item:", item));
}
for (const num of items) {
var data = { value: num };
callbacks.push(() => console.log("num:", num, "data:", JSON.stringify(data)));
}
for(var callback of callbacks){
callback();
}
How do I fix this so each function remembers its own value?