1

So it's probably some mis-understanding on the best way to use the setTimeout method provided by javascript but im having trouble implementing it in a way that makes sense.

Essentially I have an Array with numbers between 1-4 and each number corresponds to a button getting let up.

for(let i = 0;i < arr.length;i++){
        view.renderPane(arr[i]) //All this does is set the .css

view.renderPane is pretty simple:(I have a separate function that clears(sets opacity back to .5) it, but if possible i'd like to just put that in here.

  renderPane(pane){
    $("."+pane).css("opacity", "1");
    console.log("Activating Pane "+ pane)
  }

So I tried setting up a timeout thinking I could call the renderPane within the timeout, but all it did was set up a bunch of timeouts that basically fired off after X seconds (or milliseconds). Is there a way I can call the renderPane(pane) function every 1 second (to set up a delay) inside this for loop? or will I need to set up something else?

6
  • you need to call the function every 1 second : have you tried interval Commented May 5, 2017 at 3:31
  • @NairAthul Will interval prevent the for loop from running? since I would only need to call the renderPane function so many times (based on the array length) Commented May 5, 2017 at 3:34
  • yes interval will trigger every 1 second(as you provide). you can also clear / stop the timer when you want also Commented May 5, 2017 at 3:35
  • Are you trying to render the panes one after the other with a delay between each? After doing them all, do you want it to "wrap around" to the first pane (and continue indefinitely)? Commented May 5, 2017 at 3:59
  • No, basically it needs to render then clear (like a second after it renders and lights up the button). Think of like a simon game. the lights flash yellow/red/yellow/blue...etc.. and then stop (which would be my array length which represents the computers moves) Commented May 5, 2017 at 4:01

1 Answer 1

2

No need to use a loop, just create a function which continuously schedules itself with setTimeout until it's done — in this case, it removes an item from the array in each call and stops when the array is empty:

(function callee() {
    view.renderPane(arr.shift());
    if (arr.length)
        setTimeout(callee, 1000);
})();

Example: https://jsfiddle.net/2fwht35d/

There are many other ways to implement this behaviour, but this should give you a good starting point.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.