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

爱⌒轻易说出口 提交于 2019-12-04 12:12:36

You can set a timeout and cancel it if the function is called before the time limit is reached.

var timeout = setTimeout(function() {
    runCode();
}, 5000);

function runCode() {
    clearTimeout(timeout);
    ...
}

Edit: Now that I think of it, a better way to set the timeout in this instance would be

var timeout = setTimeout(runCode, 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() {
    myFunction();
}, 1000);

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

The following code uses two global variables, condition and seconds. The timer runs every second and increases seconds by 1 if condition is not true or seconds are not more than 4.

condition = false // global
seconds = 0 // global

var timer = setInterval(function() {
if (condition || seconds > 4) {
    clearInterval(timer)
}
seconds+=1;
}, 1000);
window.onload = function(){
    var timer = setTimeout(RunCode, 5000);
    function RunCode(){
        //do something
        //RunCode() already done and we don't want to run it second time
        element.onevent = function(){};
    }
    //pseudo code
    element.onevent = function(){
        clearTimeout(timer);
        RunCode();
    }
    //possibly more event handlers with similar logic
}

Isn't setTimeout what you are looking for?

setTimeout(function() {
    if (mycondition) {
        //do work
    }
}, 1000);

Will wait 1000ms and do the statement. If your boolean condition is an event based thing then you could listen for it. What causes the boolean to become true? It sounds like the timeout is irrelevant and so we just need to check the condition probably every 100ms:

setInterval(function() {
    if (mycondition) {
        //do work
    }
}, 100);

Does that help you?

So the full solution:

var mytimeout, myinterval;
mytimeout = setTimeout(function() {
        //do work
      clearInterval(myinterval);
}, 5000);
myinterval = setInterval(function() {
      if (condition) {
          clearTimeout(mytimeout);
          //dowork
      }
}, 100);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!