Search code examples
javascriptwrapperwait

Javascript wait-until-then wrapper function


There are already a few javascript wait until questions on stackoverflow. But none of them address a wrapper function.

Could anyone provide wait until functionality and then wrap it in a function like:

WaitUntilThen(condition,functiontocall);

for example:

WaitUntilThen($('#myid').css('display')=='none',PrintCalculations());

Solution

  • This can't be done literally. Arguments are evaluated before the function is called, so WaitUntilThen would just receive either true or false; depending on what the condition initially evaluated to.

    Interpreting this question as literally as possible, I think you'd need to wrap the condition in a function, then have WaitUntilThen poll the function. Something kind of like:

    function WaitUntilThen(conditionF, thenF, pollIntervalMs = 500) {
        const timer = setInterval(() => {
            const result = conditionF();
            if (result) {
                clearInterval(timer);
                thenF();
            }
        }, pollIntervalMs)
    }
    
    WaitUntilThen(() => $('#myid').css('display')=='none', PrintCalculations);
    

    This is a terrible solution though. I would simply try to change how you're approaching the problem.


    I was going to post a implementation closer to Pedro's answer, since returning a promise allows you to properly sequence code. It felt off though since if you're returning a promise, there's no need for thenF, since the caller could just use await/.then on the promise to do whatever they want after. If you're willing to abandon the callback argument, I'd go with what Pedro wrote, but just expect the caller to call PrintCalculations

    function WaitUntilThen(conditionF, pollIntervalMs = 500) {
        return new Promise((resolve) => {
            const timer = setInterval(() => {
                const result = conditionF();
                if (result) {
                    clearInterval(timer);
                    resolve();
                }
            }, pollIntervalMs);
        });
    }
    
    (async () => {
        await WaitUntilThen(() => $('#myid').css('display')=='none');
        PrintCalculations()
    });