Search code examples
javascriptpromisetry-catchqualtrics

javascript: Retrying until promise is resolved and then execute


I am checking whether some elements of my DOM are fully charged and I wanted to do it through a promise function that checks some elements and if not loaded waits for them.

This is my code

var jq = jQuery.noConflict();
var df = jq.Deferred();
function keepTrying() {
try{
var el1 = \\element to search for
var success=true
catch(e){
var success= false
}
if (success) {
    //Resolves promises
    df.resolve();
    return df.promise();
} else {
    //Here it retries.. 
    setTimeout(function() {
        keepTrying();
    }, 500);
}
}
keepTrying();
df.done(function() {
//what to do after
});

Do you think there is an easier way to do it? I am working on Qualtrics so importing external libraries could be tricky when passing from one function to another.


Solution

  • I'd use an inner recursive function, and resolve the promise when the element is found.
    You could add a count to that, and reject the promise after n tries etc.

    function keepTrying() {
    
       var def = $.Deferred();
    
       (function rec() {
            var el  = document.getElementById('something');
            if ( el === null ) {
                setTimeout(rec, 500);
            } else {
                def.resolve();
            }
       })();
    }
    
    keepTrying().done(function() { ... });