I have multiple bulbs in one array. I'm trying to turn on and off the bulbs one by one. Each bulb should be turned ON for 1 second (one by one) and then all bulbs should be OFF for 2 seconds.
But in the below code, the output is not in the expected order. Seems like the inner setTimeout()
does not follow the delay time of the outer one.
var array = [1, 2, 3, 4, 5, 6];
for (let i = 0; i < array.length; i++) {
setTimeout(function() {
console.log(i + " is on");
setTimeout(function() {
console.log(i + " is off");
}, i * 1000);
}, i * 3000);
}
I do not have to use setTimeout()
here (if there's a better alternative).
Any idea will be appreciated.