Question about setInterval in my code for the Simon game

Hi, the link to my codepen is: https://codepen.io/glennqhurd/pen/EQqxKe

The specific code I need help with is on line 93. Here’s the code block:

function buttonSequence(count) {
    for (var i = 0; i < count; i++) {
      if (moveList.length < i + 1) {
        var random = Math.floor(Math.random() * 4);
        moveList.push(colorList[random]);
      }      
      //for (var j = 0; j <= i; j++) {
      var sequence = setInterval(function() {
        switch (moveList[count]) {
          case "red":
            buttonFlashRed($("#arc1"));
            break;
          case "blue":
            buttonFlashBlue($("#arc2"));
            break;
          case "yellow": 
            buttonFlashYellow($("#arc3"));
            break;
          case "green":
            buttonFlashGreen($("#arc4"));
            break;
        }
        count++;
        if(moveList.length <= count) {
          clearInterval(sequence);
          count = 0;
        }
      }, 300);
    }
  }

The problem is when the code gets to

var sequence = setInterval(function() {

it ignores the code and skips ahead to the top of the for loop. I don’t know if it’s because of the way for loops work in Javascript but I need it because I’m trying to get the computer to generate a sequence based off of a given number and list that stores the moves. I’m stumped. (Also, it was working w/o the setInterval but the buttons would be flashing simultaneously.)

So this is also a coming interview question you may see.

Using a setTimeout or setInterval doesn’t fire as you think it would - in a blocking aka synchronise order. It gets added to the browsers ha engine runtime queue and will get fired when the queue item is ready to be fired.

So essentially you may think that your setTimeout is going to fire before your next iteration of your loop but in fact that may not be the case.

So basically you can’t use that function there in the manner.

I cleaned it up again, it only took a while to get to because I went out of town w/o a computer for four days. Now there’s one function that works for all four buttons, I just have to combine the three dicts involved into a single object w/ three properties per id.

Thank you for the advice, I’m still wrapping my brain around timers in Javascript since as you said it’s not linear.

Here is a starting point that will guide you in understanding JS more. It’s important to know HOW JS works as well as just writing it.