Home > Software design >  Promise with recursion and setTimeout
Promise with recursion and setTimeout

Time:11-05

I am trying to create a function to wait a DOM element in HTML. I want to check if element is present every 2seconds and when elements appears return a Promise to consume response using "then".

This is my code:

function checkElement(){
    console.log("Check Element...")

    if( jQuery('#idOfElement').length > 0 ){        
        return new Promise( (resolve, reject) => {
            resolve()
        })
    }
    else{
           //retry after 2 seconds
           setTimeout( () => {
            checkElement()
           },2000) 
    }
}

The problem of this code is that "then" is never executed.

checkElement().then( ()=> console.log("Element Found"))

How can I modify the code to consume the promise? Thanks

CodePudding user response:

you can return the result of the recursive call to checkElement() within the setTimeout.

when the element is not found, it returns a promise that will be resolved after a 2-second delay. It recursively calls checkElement within the setTimeout and resolves the promise once the element is found. This allows you to use .then to execute code when the element is found.

function checkElement() {
    console.log("Check Element...")

    if (jQuery('#idOfElement').length > 0) {
        return Promise.resolve(); // Return a resolved promise
    } else {
        // Retry after 2 seconds
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                checkElement().then(resolve); // Recursively call and resolve the promise when the element is found
            }, 2000);
        });
    }
}

checkElement().then(() => console.log("Element Found"))

  • Related