Reputation: 11
I have this function Offline.check();
, which takes 1 seconds to execute..So below function is not waiting for it and it always return false on first time.I used set time out..but thats always returning null.
function checkstats()
{
Offline.check(); // This returns Offline.state=up or down and it takes 1 seconds to complete.
if(Offline.state=="up")
{
return true;
}
else
{
return false;
}
}
var a = checkstats();
Upvotes: 1
Views: 522
Reputation: 864
Ideally you could set a callback function with Offline.check
, but I understand it is external, so that won't work.
You can use a timeout to wait for Offline.state
to get set, but then you'll need to do any actions involving the variable a
asynchronously too:
function checkstats(callBack){ // checkstats() now takes a callback
Offline.check(); // Start Offline.check() as usual
setTimeout(function(){ // Set a timeout for 1 second
if(Offline.state=="up") // After 1 second, check Offline.state as usual
{
callBack(true); // ...but we call the callback instead of returning
}
else
{
callBack(false); // ...but we call the callback instead of returning
}
}, 1000);
}
checkstats(function(a){ // This anonymous function is the callback we're using
// Now you can use "a" normally
});
If you're not sure that Offline.check()
will take exactly 1 second, you can use an interval instead of a timeout, and try every second for, say, 5 seconds:
function checkstats(callBack){
Offline.check();
var attempt = 0, maxAttempts = 5;
var checkStatsInterval = setInterval(function(){
if(++attempt > maxAttempts){
// Ran out of attempts, just give up
clearInterval(checkStatsInterval);
alert('Waited '+maxAttempts+' seconds for Offline data. Giving up!');
return;
}
if(Offline.state){
clearInterval(checkStatsInterval);
// It's loaded! Now confidently check Offline.state
if(Offline.state=="up")
{
callBack(true);
}
else
{
callBack(false);
}
}
}, 1000);
}
checkstats(function(a){
// Now you can use "a" normally
});
Upvotes: 1
Reputation: 176
You can use Asynchronous JavaScript to address the issue. There are several ways of implementing asynchronous behaviour in JavaScript. You can use Callbacks, Listeners or Promises.
Anyway, if you are certain that it only takes 1 second, setTimeout in a callback function and allow Offline.check()
to complete. (If it's external or lazy to implement async there)
doOfflineCheck(function(){
if(Offline.state=="up")
{
return true;
}
else
{
return false;
}
});
function doOfflineCheck(cb){
setTimeout(function(){
Offline.check();
},1000);
}
Upvotes: 0