-3

I wrote a function that when called returns just 5, yet when I console.log the function inside of the setInterval() it returns exactly what I expect. So why doesn't it work when called?

function countdown(seconds){
  var tick = 0;

  setInterval(function() {
    if (seconds > tick) {
      seconds--;
      console.log(seconds); //counts down as expected.
    }
  }, 1000);
  return seconds;

}

console.log(countdown(5)); //returns undefined.

Also, I know setTimeout() is preferred but it when I swap out setInterval it doesn't work at all. Any help and clarity with this issue would be greatly appreciated it.

London804
  • 1,072
  • 1
  • 22
  • 47
  • 3
    Because countdown does not return anything so it is undefined. What do you expect it to log? – epascarello Oct 15 '15 at 03:30
  • 1. the function executed by setInterval is run asynchronously 2. for the console.log to log anything other than undefined, the function would have to return something 3. since your edit where you return seconds, the console.log should now output 5, so you should edit your question as it is now incorrect – Jaromanda X Oct 15 '15 at 03:33
  • Yes, it returns just 5. Apologizes for not posting it that way to begin with. I messed around with it several times and forgot to add that back in. My assumption is it returns just 5 because its asynchronous? – London804 Oct 15 '15 at 03:35
  • Are you wondering why the value returned is `5` instead of `0`? Or, are you wanting it to return each value of `seconds` as it counts down? – Jonathan Lonowski Oct 15 '15 at 03:37
  • I want it to countdown as in 5, 4, 3, 2 ... – London804 Oct 15 '15 at 03:42
  • 2
    That's what it's doing. The countdown is in the log. A function can only return one time. What do you mean for it to return 5, 4, 3, 2...? – Barmar Oct 15 '15 at 03:48

1 Answers1

0

//returns undefined.

Because seconds is not defined when the function returns. See the function body. setInterval isn't called till the function returns.

function countdown(seconds){
  var tick = 0;

  setInterval(function() {
    if (seconds > tick) {
      seconds--;
      console.log(seconds); //counts down as expected.
    }
  }, 1000);

  // NOTHING HAS ASSIGNED TO seconds TILL THIS POINT
  return seconds;

}

You probably want to return something that gets resolved at a later point aka. a promise.

basarat
  • 261,912
  • 58
  • 460
  • 511
  • Okay so if I want it to return the countdown. What do I need to change? To be clear I mean countdown as in 5, 4, 3 ... – London804 Oct 15 '15 at 03:39