1

I am trying to write a recursive function which will output as audio a random sequence of letters, with a set length n, the function's only argument.

My idea was for the function to output a random letter's audio, then wait a given amount of time (using setTimeout) before calling itself with argument n-1 (the delay is necessary so that each audio file can be played in completion before the next starts).

However, when I run my code, the setTimeout seems to be ignored, as all the audio files play at once.

Relevant code:

function sayLetter(n)
{
    if (n > 0)
    {
        r = Math.floor(Math.random()*26); //Chooses random index
        sound[r].play(); 
        setTimeout(sayLetter(n-1), 1000); 
    }
}

When I call the function elsewhere in the program:

sayLetter(8);

(presumably) eight audio files all play at once.

Does anyone have any idea what is going wrong? Is it a simple mistake, or am I going about such a task in completely the wrong way?

Any help is appreciated

2 Answers2

1

You are calling the function immediately instead of calling it within setTimeouts callback.

function sayLetter(n)
{
    if (n > 0)
    {
        console.log(n)
        setTimeout(() => {
          sayLetter(n-1)
        }, 1000); 
    }
}

sayLetter(3);
nicholaswmin
  • 21,686
  • 15
  • 91
  • 167
0

I fixed the problem by switching the setTimeout from

setTimeout(sayLetter(n-1), 1000);

to

setTimeout(function() { sayLetter(n-1), }, 1000);
Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
  • 1
    Because `sayLetter(n-1)` is a function invocation, not a function reference, which setTimeout expects – Taplar Jan 15 '19 at 23:43