setTimeout does not wait for a second

setTimeout doesnt wait for a second(1000ms)

function simpleFunction(FFF) {
    const b = FFF + 1;
    console.log(b);
    setTimeout(simpleFunction(b), 1000);
};

simpleFunction(i);

this is the output after <1 second I started the program

Upvotes: 0

Views: 50

Answers (3)

Jax-p
Jax-p

Reputation: 8531

simpleFunction(b) calls function (instantly - because of ()) but setTimeout expects function to-be called. You can wrap first argument into the another function or use currying.

Example:

function simpleFunction(FFF) {
    const b = FFF + 1;
    console.log(b);
    setTimeout(function() {
      simpleFunction(b)
    }, 1000);
};

simpleFunction(1);

You can read more about setTimeout() and see more examples at MDN.

Upvotes: 1

Andy
Andy

Reputation: 63524

You're assigning the result of calling simpleFunction to the timeout not the function itself.

If you need to pass in an argument to the function that the timeout calls you can add that separately.

function simpleFunction(i) {
  const b = i + 1;
  console.log(b);
  setTimeout(simpleFunction, 1000, b);
};

simpleFunction(0);

Upvotes: 2

kozko
kozko

Reputation: 31

You're directly calling the function simpleFunction(b) you should give it a function instead () => simpleFunction(b)

function simpleFunction(FFF) {
    const b = FFF + 1;
    console.log(b);
    setTimeout(() => simpleFunction(b), 1000);
};

simpleFunction(1);

Upvotes: 2

Related Questions