Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()
like image 530
Bram Vanroy Avatar asked Sep 02 '25 09:09

Bram Vanroy


1 Answers

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
}
like image 193
Bram Vanroy Avatar answered Sep 05 '25 00:09

Bram Vanroy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!