0

I have the following code :

var i = 0, count = 10, randomId;

    function f(myArray) {

          // this will get a random value from myArray
        randomId = myArray[Math.floor( Math.random()*myArray.length )]; 

          // displays the random value
        alert (randomId);


        i++;
        if( i < count ){
            setTimeout( f, 3000 );
        }
    }

    f(myArray);

The above code works but gives only one alert and then it stops.

However it works properly (10 loops) with basic alerts such as alert("hi"), and remove the randomId line.

It's as if anything complex within this function will block the loop, it will only handle basic alerts..

Any help is appreciated, thanks :)

6
  • 4
    You're calling f(myArray), but where is myArray? Your recursive call doesn't pass anything to f, so it will be undefined, thus creating an error when you do myArray.length Commented May 9, 2016 at 15:29
  • myArray was created previously. So the first alert will work fine, returning eg. 42 Commented May 9, 2016 at 15:30
  • Then do setTimeout(f, 3000, myArray) Commented May 9, 2016 at 15:31
  • Nvm now i understand it, thanks ! Commented May 9, 2016 at 15:32
  • 2
    ...just be aware that it won't work in old IE and old Firefox. To support those, you'd need setTimeout(function() { f(myArray) }, 3000) Commented May 9, 2016 at 15:32

1 Answer 1

3

In your setTimeout you are not passing the array:

Try this:

    if( i < count ){
        setTimeout(() => f(myArray), 3000 );
    }

^ that creates a lambda function so that you can pass a value to your callback in the timeout.

var i = 0, count = 10, randomId;

    function f(myArray) {

          // this will get a random value from myArray
        randomId = myArray[Math.floor( Math.random()*myArray.length )]; 

          // displays the random value
        alert (randomId);


        i++;
        if( i < count ){
            setTimeout(() => f(myArray), 3000 );
        }
    }

    f([1,2,3,4,5,6,7,8]);

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

2 Comments

it is ok but it will fail it browser does not support ES6.
@ZohaibIjaz true. in those browsers you can just use function () { f(myArray); } instead, or use a transpiler :-)

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.