I have this function which pings my server for a specific change in data:
function connected() {
$.ajax({
success : function(d) {
if (d.success) {
// return data
} else {
setTimeout(connected, 200);
}
}
});
}
(Obviously the code has been stripped to the bare minimum to make my intentions clearer)
What I want to do is return a bool true when it gets found, so I can go
if (connected()) {
// process data
}
(obviously the data is stored in a global variable.)
Is there any way to achieve this?
EDIT
I could create a ‘pause’ function:
function pauseScript(ms) {
ms += new Date().getTime();
while (new Date().getTime() < ms) {}
}
Then change my code to exclude setTimeout() (and include some other stuff)
function connected() {
var value;
$.ajax({
async: false,
success : function(d) {
if (d.success) {
// set data
value = true;
} else {
pauseScript(200);
value = connected();
}
}
});
return value;
}
However this feels a little hacky!
For doing that the best should continue in async mode :
Maybe, i’m not so sure in this case, you will need to bind this (I mean binding scope) :
http://www.robertsosinski.com/2009/04/28/binding-scope-in-javascript/