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

Delay before recursive function call

I’m trying to set a delay before every recursive function call. Currently, it’s returning undefined. The problem might be the scope of the recursive call (inside settimeout and then).
I tried it like this:

    function delay(ms) {
        return new Promise(resolve => {
            setTimeout(resolve, ms)
        });
    } 

    const checkIfListElementIsRendered = (className) => {
        delay(10).then(function (res) {
            if (document.getElementsByClassName(className)[0]) {
                return true;
            }
            return checkIfListElementIsRendered(className);
        })
    }

And this:

    const checkIfListElementIsRendered = (className) => {
        if (document.getElementsByClassName(className)[0]) {
            return true;
        }
            
        setTimeout(() => {
            return checkIfListElementIsRendered(className);
        }, 10);   
    }

Any help is appreciated!

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

>Solution :

You need to turn checkIfListElementIsRendered to async/await syntax, and await the delay and checkIfListElementIsRendered methods, Also instead return true turn it to promise to be always return a promise.

When you call checkIfListElementIsRendered method outside, you need to resolve it with await or then callback.

function delay(ms) {
    return new Promise(resolve => {
        setTimeout(resolve, ms)
    });
} 

const checkIfListElementIsRendered = async (className) => {
   await delay(10)
   if (document.getElementsByClassName(className)[0]) {
      return Promise.resolve(true);
   }
   return await checkIfListElementIsRendered(className);
}
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