Why its console logging that's not a number?

Hello, here is my code:

const levels = {
  easy: 5,
  medium: 3,
  hard: 2
}

let time = parseInt(levels.easy);

setInterval((time) => {
  time --;
  console.log(time)
}, 1000)

It’s console logging every time NaN, why is that?

Remove time inside the parentheses.

setInterval(() => {
  time--;
  console.log(time)
}, 1000)
1 Like

If you want to pass arguments to the callback you can use the arguments parameters, see the example given on MDN.

setInterval(() => {  
  time--;
  console.log(time)
}, 1000, time)

8.6 Timers

handle = self . setInterval( handler [, timeout [, arguments... ] ] )

Schedules a timeout to run handler every timeout milliseconds. Any arguments are passed straight through to the handler.

If the first method argument is a Function

Invoke the Function. Use the third and subsequent method arguments (if any) as the arguments for invoking the Function.

The reason why you are getting NaN is that time is undefined inside the callback. It just becomes a local variable inside the callback and it gets redeclared every time the callback runs.

setInterval((time = 1) => {
  console.log(time);
  time--;
  console.log(time)
}, 1000)
// 1
// 0
// 1
// 0
2 Likes