-1

I have this code:

function printDelay(j) {
  if (j != 0) {
    setTimeout(() => {
      console.log(j);
    }, 1000);
    j--;
    print(j);
  } else {
    console.log("END!");
  }
}

printDelay(5);

Why it doesn't print the numbers 5,4,3,2,1 with a delay of 1 second?

Vlad U
  • 5

1 Answers1

3

You need to fix a typo where you call print(j) instead of printDelay(j); also you must move it (as well as the j-- line) inside the callback of setTimeout.

function printDelay(j) {
  if (j != 0) {
    setTimeout(() => {
      console.log(j);
      j--;
      printDelay(j);
    }, 1000);
   
  } else {
    console.log("END!");
  }
}

printDelay(5);
WillD
  • 5,170
  • 6
  • 27
  • 56