Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get return value from setTimeout [duplicate]

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()); 
like image 569
Vainglory07 Avatar asked Jul 24 '14 08:07

Vainglory07


People also ask

Can you return value from setTimeout?

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 ()?

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.

How do I return a function from setTimeout?

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); };

Does setTimeout repeat?

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.


2 Answers

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!'; } 
like image 82
Matt Clarkson Avatar answered Sep 25 '22 03:09

Matt Clarkson


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(); 
like image 37
Quentin Avatar answered Sep 25 '22 03:09

Quentin