Sunday, 11 March 2018

JavaScript closure inside loops – simple practical example



var funcs = [];

// let's create 3 functions
for (var i = 0; i < 3; i++) {
// and store them in funcs
funcs[i] = function() {
// each should log its value.
console.log("My value: " + i);
};
}
for (var j = 0; j < 3; j++) {
// and now let's run each one to see

funcs[j]();
}





It outputs this:




My value: 3
My value: 3
My value: 3





Whereas I'd like it to output:




My value: 0
My value: 1
My value: 2








The same problem occurs when the delay in running the function is caused by using event listeners:





var buttons = document.getElementsByTagName("button");
// let's create 3 functions
for (var i = 0; i < buttons.length; i++) {
// as event listeners
buttons[i].addEventListener("click", function() {
// each should log its value.

console.log("My value: " + i);
});
}











… or asynchronous code, e.g. using Promises:





// Some async wait function
const wait = (ms) => new Promise((resolve, reject) => setTimeout(resolve, ms));

for (var i = 0; i < 3; i++) {

// Log `i` as soon as each promise resolves.
wait(i * 100).then(() => console.log(i));
}





What’s the solution to this basic problem?

No comments:

Post a Comment

casting - Why wasn&#39;t Tobey Maguire in The Amazing Spider-Man? - Movies &amp; TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...