I just want to get the return value from setTimeout
but what I get is a whole text format of the function?
function x () { setTimeout(y = function () { return 'done'; }, 1000); return y; } console.log(x());
You can't get a return value from the function you pass to setTimeout . The function that called setTimeout ( x in your example) will finish executing and return before the function you pass to setTimeout is even called.
Which method receives the return value of setTimeout() to cancel future invocations? Explanation: setTimeout() returns a value that can be passed to clearTimeout() to cancel the execution of the scheduled function. The ID value returned by setTimeout() is used as the parameter for the clearTimeout() method.
To get return value from setTimeout with JavaScript, we can create a promise from the setTimeout code. const x = () => { const promise = new Promise((resolve, reject) => { window. setTimeout(() => { resolve("done!"); }); }); return promise; }; const y = async () => { const result = await x(); console. log(result); };
setTimeout allows us to run a function once after the interval of time. setInterval allows us to run a function repeatedly, starting after the interval of time, then repeating continuously at that interval.
You need to use Promises for this. They are available in ES6 but can be polyfilled quite easily:
function x() { var promise = new Promise(function(resolve, reject) { window.setTimeout(function() { resolve('done!'); }); }); return promise; } x().then(function(done) { console.log(done); // --> 'done!' });
With async
/await
in ES2017 it becomes nicer if inside an async
function:
async function() { const result = await x(); console.log(result); // --> 'done!'; }
You can't get a return value from the function you pass to setTimeout
.
The function that called setTimeout
(x
in your example) will finish executing and return before the function you pass to setTimeout
is even called.
Whatever you want to do with the value you get, you need to do it from the function you pass to setTimeout
.
In your example, that would be written as:
function x () { setTimeout(function () { console.log("done"); }, 1000); } x();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With