I’m trying the following:
var timeout = 300;
var colors = ['aqua', 'limegreen']
for (var i=0; i < 4; ++i) {
console.log(colors[i % colors.length]);
setTimeout(function() { changeColor(colors[i % colors.length]) }, i * timeout);
}
function changeColor(color) {
console.log(color);
}
This doesn’t work because the parameter for changeColor is resolved when it get’s executed…this means, the color will always be the same. In my chrome it also didn’t work to pass the params after the timeout:
var color = colors[i % colors.length];
setTimeout(function() { changeColor() }, i * timeout, color);
Well, I now have a workaround with an interval which works…but since I’m here to learn….how is this done with a timeout?
The anonymous function which calls
changeColorwill be executed when for cycle will be ended already. So it will equal to the last value it gets. To prevent this capture the value you need in closure by wrapping the call to setTimeout with anonymous function: