Home > Net >  setTimeout does not wait for a second
setTimeout does not wait for a second

Time:09-02

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 programm enter image description here

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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.

  • Related