经过一段时间或满足条件后运行代码 [英] Run code after some time has passed or a condition is met
问题描述
编写代码的最佳方式和最干燥方式是什么,只要经过一段时间(例如5秒)或满足某些条件(例如,bool = true
),就可以执行-以先到者为准.从脚本第一次运行开始,将有五秒钟的时间开始计时,并且布尔值是由另一个函数更改的全局值.我认为您不能将超时和bool-check结合在一起使用,但是另一种好的方法也很好.
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.
伪代码:
if (bool = true OR timePassed = 5000):
runCode()
推荐答案
没有一个答案实际上提供了该问题的完整答案,即先到先得未实现-或最后一个代码运行两次.
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
}
这篇关于经过一段时间或满足条件后运行代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!