0
$('#start-button').click(function(){
        if(power === true)
        {
                $(this).toggleClass('on');
                if(start === true)
                {
                    start = false;
                }
                else
                {
                    start = true;
                    alert("hello");
                    while(count < 20)
                    {
                        num = Math.floor(4*Math.random());
                        simon.push(moves[num]);
                        soundNums.push(num);
                        var tempCount = count+1;
                        var start = 0;
                        while(tempCount > 0)
                            {
                                delayMove(tempCount);
                            }
                        var timeDelay;
                        function delayMove(index) {
                            timeDelay = setTimeout(move(index), 500);
                        }

                        function move(index) {
                            $(simon[index]).fadeOut(200).fadeIn(200);
                            (sounds[soundNums[index]]).play();
                            start++;
                            tempCount--;
                        }



                        count++;
                        $("p").text(count); 
                    }
                }
}
    });

So i moved the functions outside and have things I think mostly correct, only problem is now the setTimeout doesn't work. I was hoping this would fix the issue with closures by moving the counting variable into the delayed function.

Zack Lucky
  • 671
  • 3
  • 10
  • 25
  • Aside from the issue covered by the linked original, you have a second error: You're trying to use *function declarations* (such as your `function delayMove() { ... }`) where they're not allowed. They're only allowed at the top level of global or function scope, not with blocks. To create a function within a block, you must use a *function expression*. See the linked original for the syntax for that. – T.J. Crowder Apr 04 '16 at 14:10
  • Hey could you take a look now that I made an edit. Am I still massively misunderstanding this or am I getting closer? – Zack Lucky Apr 04 '16 at 15:08
  • In `timeDelay = setTimeout(move(index), 500);`, you're *callling* `move(index)` and passing its return value to `setTimeout`, exactly like `foo(bar())` *calls* `bar` and passes its return value to `foo`. If you want to call `move` later, when the timeout expires, use `timeDelay = setTimeout(function() { move(index) }, 500);` or `timeDelay = setTimeout(move.bind(null, index), 500);` – T.J. Crowder Apr 04 '16 at 15:22

0 Answers0