tempse
tempse

Reputation: 51

JS - my loop using setTimeout stops looping

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 :)

Upvotes: 0

Views: 48

Answers (1)

Tuvia
Tuvia

Reputation: 869

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]);

Upvotes: 3

Related Questions