java settimeout,如何让Java脚本的setTimeout在函数返回值

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).

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.

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

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

}

解决方案

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

});

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值