如何使 Javascript setTimeout 在函数中返回值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25129057/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 04:00:08  来源:igfitidea点击:

how to make Javascript setTimeout returns value in a function

javascriptasynchronoussettimeout

提问by Aberel

I have a function that calls some service and returns the response. If the response is FALSE, it waits 1 second to ask the service again (which then probably returns TRUE).

我有一个函数可以调用一些服务并返回响应。如果响应为 FALSE,则等待 1 秒再次询问服务(然后可能返回 TRUE)。

How can I do to call my function "checkService()" once, and get the real value? (the first or second try, decided by the function) I set the RET value inside the function, but the functions always return the first RET, because the setTimeout is asynchronous.

我怎样才能调用我的函数“checkService()”一次,并获得真正的价值?(第一次或第二次尝试,由函数决定)我在函数内部设置了 RET 值,但函数总是返回第一个 RET,因为 setTimeout 是异步的。

In other words, I need some "sleep" trick, or any solution (may be jQuery too).

换句话说,我需要一些“睡眠”技巧或任何解决方案(也可能是 jQuery)。

function checkService() {

  //this may return TRUE or FALSE
  var RET = someServiceResponse(); 

  // here waits 1 second, then ask the service again
  if( RET == true ) {
    return true;
  } else {

    setTimeout(
        function() {
            //it must return the second response of the service
            RET = someServiceResponse();  
        }, 
        1000
    );

    // I want the checkService() return the response after de timeout
    return RET;  
  }
}

function alertResponse() {
    alert( checkService() );
}

回答by Rapha?l Malié

You should use a callback function when you expect a result from the service.

当您期望服务的结果时,您应该使用回调函数。

Like this :

像这样 :

function checkService(callback) {

    //this may return TRUE or FALSE
    var RET = someServiceResponse();

    // here waits 1 second, then ask the service again
    if( RET == true ) {
        callback(RET);
    } else {

        setTimeout(
                function() {
                    //it must return the second response of the service
                    RET = someServiceResponse();
                    callback(RET);
                },
                1000
        );

        // I want the checkService() return the response after de timeout
        return RET;
    }
}

So when you want to call the service, you just need to do :

因此,当您想调用该服务时,您只需要执行以下操作:

checkService(function(status){
    alert(status);

    // Here some code after the webservice response
});

回答by elzi

Googling 'javascript setTimeout callback' here's a handy jsFiddle about 3 results down:

谷歌搜索“javascript setTimeout 回调”,这是一个方便的 jsFiddle,大约有 3 个结果:

getData('http://fakedomain1234.com/userlist', writeData);

document.getElementById('output').innerHTML += "show this before data ...";

function getData(dataURI, callback) {
    // Normally you would actually connect to a server here.
    // We're just going to simulate a 3-second delay.
    var timer = setTimeout(function () {
        var dataArray = [123, 456, 789, 012, 345, 678];
        callback(dataArray);
    }, 3000);
}

function writeData(myData) {
    console.log(myData);
}

http://jsfiddle.net/cwbuecheler/Y9Ca8/

http://jsfiddle.net/cwbuecheler/Y9Ca8/