gpt4 book ai didi

javascript - 返回 true/false 时 Node.js 停止函数

转载 作者:行者123 更新时间:2023-12-02 15:21:27 25 4
gpt4 key购买 nike

我对 Node.js 有点陌生,并且对如何实现我的目标感到困惑。

我有一个这样的函数:

function Timer() {
setTimeout(function() {
finish();
return true;
}, 60000);

setInterval(function() {
if (fail()) {
return false;
}
}, 5000);
}

此函数被调用一次,并且当其中的函数之一返回某些内容时应该停止。函数 fail() 基本上只是掷骰子,有 5% 的机会返回 false

函数 finish() 只是在超时结束时返回 true

一旦函数在某处返回某些内容,如何完全退出该函数?

最佳答案

使用变量来存储间隔和超时,以便当您的 end 函数满足您的要求时,您可以使用 clearInterval/clearTimeout所需的条件(或超时完成),并且您应该将回调传递给您的 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);
}

现在,您的回调将收到 true/false,具体取决于哪个回调首先被调用。

Timer(function(condition) {
if (condition) doSomethingWhenConditionIsTrue();
else doSomethingWhenConditionIsFalse();
});

关于javascript - 返回 true/false 时 Node.js 停止函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34007685/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com