Search code examples
javascriptjqueryconditional-statementssettimeout

Run code after some time has passed or a condition is met


What is the best and DRYest way to write code that can be executed either when some time has passed (say, 5 seconds) or some condition is met (e.g. bool = true) - whichever comes first. The five seconds start counting from when the script first ran, and the boolean is a global that is changed by another function. I don't think you can combine the time out and the bool-check in one statement, but another good way is also good.

Pseudo code:

if (bool = true OR timePassed = 5000):
    runCode()

Solution

  • None of the answers actually provide a full answer to the question, namely the whichever comes first is not implemented -- or the final code is run twice.

    You need a timer, and a condition (as other answers suggested but failed to combine in one whole).

    var done = false;
    var thisTimeout = setTimeout(function() {
        myFunction();
    }, 1000);
    
    if ((someCondition) && !done) {
        myFunction();
    }
    function myFunction() {
        clearTimeout(thisTimeout);
        done = true;
        // Do stuff
    }