0

Here is a minimal replicable code:

function print(num) {
   console.log(num)
}

...later in the code

var num = 5;
var count = 0;
while (num != 0) {
   setTimeout(function() {print(num);}, 1000 * count)
   num--;
   count++;
}

I want my output to be 5 4 3 2 1 but instead my output is 0 0 0 0 0

Why is this?

Jonathan Allen Grant
  • 3,408
  • 6
  • 30
  • 53

2 Answers2

1

In this function call to setTimeout():

setTimeout(print(num), 1000 * count)

you're calling your print() function and passing its return value. If you want print() to be called when the timer expires, you have to pass a function to call it:

setTimeout(function() { print(num); }, 1000 * count)
Pointy
  • 405,095
  • 59
  • 585
  • 614
0

You must pass in the value of num at the time through the setTimeout function, if you wish for the value at that point in time to be used

function print(num) {
   console.log(num)
}

var num = 5;
var count = 0;
while (num != 0) {
   setTimeout(print, 1000 * count, num);
   num--;
   count++;
}
Joseph Young
  • 2,758
  • 12
  • 23