Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Promise with recursion and setTimeout

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

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

>Solution :

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"))

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading