Reputation: 1937
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.
Upvotes: 2
Views: 1873
Reputation: 12988
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() {
});
Upvotes: 4
Reputation: 758
If not using promises, you can also traditionally use a callback.
function checkLoading(callback) {
console.log('checking loading');
if ($('div.vX.UC').css('display') === 'none') {
console.log('Loading Complete');
callback();
} else {
setTimeout(function() {
checkLoading();
}, 500)
}
}
Would be used like this:
checkLoading(function() {
// do something
});
Upvotes: 2
Reputation: 2475
You Should try like below :
function checkLoading() {
var dfrd1 = $.Deferred();
console.log('checking loading');
if ($('div.vX.UC').css('display') === 'none') {
console.log('Loading Complete');
dfrd1.resolve("Loading Completed");
} else {
setTimeout(checkLoading, 500)
}
return dfrd1.promise();
}
Upvotes: 0