使用一个变量来存储间隔和超时,这样您就可以使用clearInterval
/clearTimeout
当你end
功能满足您的所需条件(或超时完成),你应该传递一个回调到您Timer
功能,所以你能够返回一次的时间间隔或超时完成值:
function Timer(myCallback) {
var myInterval, myTimeout;
myTimeout = setTimeout(function() {
finish();
clearInterval(myInterval); //Clear the interval so that the callback won't be called again.
myCallback(true); //Call your callback function passing true.
}, 60000);
myInterval = setInterval(function() {
if (fail()) {
clearInterval(myInterval); //Clear the interval so that the callback won't be called again.
clearTimeout(myTimeout); //Clear the timeout so that the callback won't be called again.
myCallback(false); //Call your callback function passing false.
}
}, 5000);
}
现在你的回调将得到真/假取决于哪一个被先叫。
Timer(function(condition) {
if (condition) doSomethingWhenConditionIsTrue();
else doSomethingWhenConditionIsFalse();
});
你想写什么逻辑?骰子? – Ben