setTimeout() is giving me error: Timeout { _called: false}

Viewed 59

I am trying to make a function that generates a random number then adds 5 to it after 3 seconds

so here's what I tried to do:

const add5=(randomNum)=>{
         return randomNum+5
}
// Function for you to get started with:
const generateRandomNumber = () => { 
    const rand = Math.round(Math.random() * 10);
    // ....
  console.log(rand)
 console.log(setTimeout(add5,3000,rand))
}
generateRandomNumber()

now I am trying to console.log the results to see what I am implementing in action. when I ran the code; I got the result as follows:

9
Timeout {
  _called: false,
  _idleTimeout: 3000,
  _idlePrev: 
   TimersList {
     _idleNext: [Circular],
     _idlePrev: [Circular],
     _timer: Timer { '0': [Function: listOnTimeout], _list: [Circular] },
     _unrefed: false,
     msecs: 3000,
     nextTick: false },
  _idleNext: 
   TimersList {
     _idleNext: [Circular],
     _idlePrev: [Circular],
     _timer: Timer { '0': [Function: listOnTimeout], _list: [Circular] },
     _unrefed: false,
     msecs: 3000,
     nextTick: false },
  _idleStart: 141,
  _onTimeout: [Function: add5],
  _timerArgs: [ 9 ],
  _repeat: null,
  _destroyed: false,
  [Symbol(asyncId)]: 7,
  [Symbol(triggerAsyncId)]: 1 }

I can assume that 9 is the random number because it kept changing whenever I re-ran the code my question simply is: 'why setTimeout() is not working while it actually should be?'

1 Answers

You are logging the output of the setTimout function itself, when what (I think) you want is to log the return value from your add5 function.

const add5 = (randomNum) => {
    return randomNum + 5
}

const generateRandomNumber = () => { 
    const rand = Math.round(Math.random() * 10);
    // ....
    console.log(rand)
    setTimeout(r => console.log(add5(r)), 3000, rand)
}

generateRandomNumber()
Related