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).<
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
});
Googling 'javascript setTimeout callback' here's a handy jsFiddle about 3 results down:
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/