Bram Vanroy Bram Vanroy - 5 months ago 11x
Javascript Question

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


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() {
}, 1000);

if ((someCondition) && !done) {
function myFunction() {
    done = true;
    // Do stuff