My function includes a timeout that changes every 3 seconds:
setActiveImage(promotions) {
for (let i = 0; i <= promotions.length - 1; i++) {
setTimeout(()=> {
this.activeImage = 'http://myrul/public/Commercials/' + promotions[i].commercial_file[0].file;
}, 3000*(i)); //CHANGE PICTURE EVERY 3s
}
}
Now, I want to replace the fixed time (3000) with a variable obtained from promotions. Here is the relevant information from https://i.sstatic.net/CbKdG.png
Each picture, or instance of i, should have its own specific time duration.
Here is my attempt:
for (let i = 0; i <= promotions.length - 1; i++) {
var x = promotions[i].time; //GET TIME
var y = +x; //TURN STRING TO NUMBER
var z = y * 1000; //TURN SECOND INTO MILISECONDS
var promoDisplayTime = z; //CUSTOM TIME
setTimeout(()=> {
this.activeImage = 'http://myurl/Commercials/' + promotions[i].commercial_file[0].file;
}, promoDisplayTime*(i));
}
Despite using the correct variable promoDisplayTime, the timer seems to be inaccurate. For instance, the first picture should last 4 seconds, but it only lasts 3 seconds. The second picture should be displayed for 3 seconds, but it lasts 6 seconds. The third picture should be shown for 10 seconds, but it only lasts 4 seconds...
I am unsure of what I am doing wrong. Why is the timer off even with the correct time value?
For a demonstration with dummy data, please visit this StackBlitz link