I have the following array.[{startColor:"red",event:"start",time:0.3},{stopColor:"blue",event:"stop",time:10},{startColor:"green",event:"start",time:40}] . I'm looping through the array and for each settimeout period, I want to like freeze the code for that given period in the time section of each array element using the settimeout and display the corresponding color for the number of seconds in the array element. . example . for each array element settimeout(function, time_from_the_element) . The Challenge am facing is, it's making the loop but after the first element has been looped, settimeout doesn't restart afresh for the second element . That is, say the first element took 14 seconds and the next element is to take 16secs and so after the first 14 seconds, it only takes two seconds until the next element is called although I want after first 14 seconds, settimeout restarts at 0 and counts to 16 again and so and so. It has taken me a whole day to try solve it out.
The other challenge am facing is, after the last loop in the array I want to clear the last element color from the display.That is after the last element has been looped and that's appearing tricky.
NB: setClockBackgrouco and setbackgroucol are functions am using to display the colors and can be replaced by console.log in this scenario.
const changeColors = async () => {
const dat2 = await new Promise((resolve) => {
for (let i = 0; i < data.length; i++) {
console.log("data i is:", data[i]);
if (data[i].event === "start") {
setTimeout(() => {
console.log("Start: ", data[i].event);
setClockBackgroucol(null);
setbackgroucol(data[i].startColor);
}, data[i].programtime * 1000);
} else if (data[i].event === "stop") {
setTimeout(() => {
console.log("Stop: ", data[i].event);
setClockBackgroucol(data[i].stopColor);
setbackgroucol(null);
console.log(
"time taken is ",
data[i].time. * 1000
);
}, data[i].time * 1000);
}
console.log("should have been called last");
}
});
};