You're returning n
from the callback you pass to setTimeout
- not the outside function. In actuality, your wait
function returns a ID of a timeout returned from setTimeout
. The only way you can really "delay returning" is to use a Promise and resolve after a timeout:
const wait = n => new Promise(resolve => setTimeout(() => resolve(n), n * 1000));
Then:
wait(5).then(n => console.log(n)) //5
Then wait
returns a Promise that resolves in 5 seconds to n
which you can access via Promise#then
. With promises, you can also utilize async
and await
from ES2016 to get a closer result to what you want:
const wait = n => new Promise(resolve => setTimeout(() => resolve(n), n * 1000));
(async () => {
console.log(await wait(5));
})();
What await
does is await for a promise to resolve. So await wait(5)
waits for the promise returned from wait
to resolve (which is after 5 seconds). Then, it logs the resolved value. You'll also notice it's wrapped in an async immediately executes arrow function. To use await
you need to be in an async
function.