2

The reason why its not possible is: The function that called setTimeout will finish executing and return before the function you pass to setTimeout is even called.

What I don't understand: Even if the outer function has finished executing, since its a a setTimeout and not just an inner function, it is scheduled to execute later. That means function I pass to setTimeout WILL execute regardless of outer function. If I add a console.log to my setTimeout function, it will log because said function will get executed so why cant I return a value then?

function x () {
  setTimeout(() =>{
    console.log("logging")
    return "hello"
  }, 2000)
}
x()


function x () { //here it makes sense that nothing gets returned as inner function is not called
  return () =>{
    console.log("logging")
    return "hello"
  }
}
x()
j08691
  • 204,283
  • 31
  • 260
  • 272
  • 1
    In first example your `return 'hello'` will be handled by `setTimeout` (just discarded). In second example you return function, so `x()()` would call inner function and get `hello` – Justinas Jun 03 '20 at 13:57
  • If you put an order in to the milkman to have a pint of milk tomorrow morning, then you'll get a pint of milk *tomorrow morning*. You won't get it immediately. – Quentin Jun 03 '20 at 13:59
  • 1
    @Quentin I think his question is different. He's asking why does't `setTimeout` return "hello" after 2 sec just as it prints "logging" – ABGR Jun 03 '20 at 14:01
  • @RahulDwivedi — That's exactly the same. – Quentin Jun 03 '20 at 14:04
  • @Quentin yes, but I would get it later. so why dont I get it later (in 2 ms in this case)? –  Jun 03 '20 at 14:41
  • Because its too late. Time doesn't stop when you put an order in with the milkman. You aren't left standing waiting for the milk to turn up unable to do anything else. You get the function's return value immediately. – Quentin Jun 03 '20 at 14:42
  • sorry i just dont get it. can you please explain what you mean with "You get the function's return value immediately."? Also how is it possible that console.log logs something then? –  Jun 03 '20 at 14:47

0 Answers0