So I have this function that has a timeout that changes every 3s:
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 change the time (3000) to a custom variable that I get from promotions. This is promotions:
So every picture, or instance of i, has it's own time.
Here is what I did:
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));
}
This in theory should work, but the timer goes way off. The first picture should last 4s, but lasts 3s. The second picture should last 3s but lasts 6s. Third picture should be 10s but lasts 4s...
I don't see what I am doing wrong. Why is the timer off even though I am sending the correct variable promoDisplayTime.
StackBlitz with dummy data: https://stackblitz.com/edit/angular-r6ejw9?file=src%2Fapp%2Fapp.component.html