chirag satapara chirag satapara - 10 months ago 36
Javascript Question

wait until function return result in jquery

I want

true
in the result , when function
checkLoading()
is call.

I have one jquery function:

function checkLoading() {
console.log('checking loading');
if ($('div.vX.UC').css('display') === 'none') {
console.log('Loading Complete');
return true;
} else {
setTimeout(function() {
checkLoading();
}, 500)
}
}


I am calling this function like below:

if(checkLoading()){
// do something
}


But above function return
undefined
and not wait for the
final
return.

I tried this using
Deferred
. But this is not working, I tried below solution:

function checkLoading() {

var dfrd1 = $.Deferred();
console.log('checking loading');
if ($('div.vX.UC').css('display') === 'none') {
console.log('Loading Complete');
return dfrd1.promise();
} else {
setTimeout(function() {
checkLoading();
}, 500)
}

// return dfrd1.resolve();
//return false;
}

checkLoading().done(function() {

// do something.
});


But this solution doesn't work for me.

Answer Source

You need to return the promise and resolve it, not "promise" it

var dfrd1 = $.Deferred();
function checkLoading(dfd) {
   console.log('checking loading');
   if ($('div.vX.UC').css('display') === 'none') {
     console.log('Loading Complete');
     return dfd.resolve();
   } else {
      setTimeout(function() {checkLoading(dfd)}, 500)
   }

   return dfd.promise();
}

checkLoading(dfrd1).then(function() {

});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download