1

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");
     
      }
    });
  
  };

2 Answers 2

3

Try this way

async function changeColors() {
  const array = [
    { startColor: "red", event: "start", time: 3000 },
    { stopColor: "blue", event: "stop", time: 1000 },
    { startColor: "green", event: "start", time: 4000 },
  ];
  for (const object of array) {
    switch (object.event) {
      case "start": {
        console.log(object.startColor);
        await delay(object.time); // in milliseconds
        break;
      }
      case "stop": {
        console.log(object.stopColor);
        await delay(object.time); // in milliseconds
        break;
      }
      default:
        continue;
    }
  }
}

function delay(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}
changeColors()

Sign up to request clarification or add additional context in comments.

2 Comments

This is a nice way of solving the problem! delay(ms) is a function that does exactly what it's name suggests: it delays further operation in the calling (async!) function by ms milliseconds. In my opinion there should be final call in the async function resetting (or hiding) the last color after the for loop has finished. Otherwise the last displayed color (green) will remain there forever and will not be hidden again after the allocated time (4000 ms).
Wow!. Thankyou so much for that. It worked only that it doesn't reset the last color after the loop has finished and in that case, immediately after the for loop I did call the functions to set the colors to null in order to clear any color in state. And it worked fine. Thankyou so much again
1

This is just a snippet (based on @Pawan Bishnoi's answer) to demonstrate that the switch can be easily replaced by a simple expression and that a final "reset" call would remove the last set color. Otherwise I think that Pawan created an excellent answer that deserved to be chosen as the "correct" one.

async function changeColors() {
  const array = [
    { startColor: "red", event: "start", time: 300 },
    { stopColor: "blue", event: "stop", time: 10000 },
    { startColor: "green", event: "start", time: 4000 },
  ];
  for (const o of array) {
    console.log(o[o.event+"Color"]);
    await delay(o.time); // in milliseconds
  }
  console.log("no color");
}

function delay(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}
changeColors()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.