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();
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)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 variablea
asynchronously too: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: