Get return value from setTimeout [duplicate]

喜你入骨 提交于 2019-12-17 07:12:29

问题


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

回答1:


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!';
}



回答2:


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



回答3:


Better to take a callback for function x and whatever task you want to perform after that timeout send in that callback.

function x (callback) {
    setTimeout(function () {
        callback("done");
    }, 1000);
}

x(console.log.bind(console)); //this is special case of console.log
x(alert) 



回答4:


You can use a combination of Promise and setTimeOut like the example below

let f1 = function(){
    return new Promise(async function(res,err){
        let x=0;
        let p = new Promise(function(res,err){
            setTimeout(function(){
                x= 1;
                res(x);
            },2000)
        })
        p.then(function(x){
            console.log(x);
            res(x);
        })


    });
}



回答5:


I think you want have flag to know event occured or no. setTimeout not return a value. you can use a variable to detect event occured or no

var y="notdone";
   setTimeout(function () {
         y="done";
    }, 1000);

You can access variable y after timeout occured to know done or not



来源:https://stackoverflow.com/questions/24928846/get-return-value-from-settimeout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!