Node.js在返回true/false时停止函数
Node.js stop function when return true/false
我对Node.js有点陌生,对如何实现我的目标感到困惑。
我有一个这样的功能:
function Timer() {
setTimeout(function() {
finish();
return true;
}, 60000);
setInterval(function() {
if (fail()) {
return false;
}
}, 5000);
}
这个函数get被调用一次,应该在其中一个函数返回某个值时停止。函数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();
});
您的函数是异步的,这意味着在setTimeout
和setInterval
之后,它退出,不返回任何值。在JavaScript函数被设计为异步的情况下,它们不能停止主线程。
JavaScript使用从运行到完成的执行模型,setTimeout
和setInterval
是异步的。这意味着您必须在稍后调用的函数中提供延续逻辑。你有三个选择:
- 回调
- 承诺
- 推论(仅当您在现代运行时)
请澄清你想要的逻辑,我会补充这个答案。
相关文章:
- 如何使以下函数返回true或false
- 如何使函数将属性值从 FALSE 设置为 TRUE
- 从异步函数返回true/false以用于同步if()
- jQuery .preventDefault 和 .stopPropagation 在返回 false 的函数中使用
- 函数返回undefined而不是true/false
- Javascripts 中的字符函数是 ret false,即使字符不满足 if 条件
- 使用函数将 V-show 设置为 true 或 false
- 函数:根据字符串中是否存在子字符串返回 True/False
- 如何将 ng-show 与控制器中返回 true/false 的函数一起使用
- 每当布尔值在 JavaScript 中变为 false 时调用函数
- 函数() { return false; } 的操作细节().
- 当函数在 Javascript 中将其设置为 true 时,布尔值返回 false
- JavaScript 函数总是返回 true,即使验证是 false
- 获取 Ajax 函数以返回 true 或 false
- 为什么函数在循环中只检查一个值后返回 false
- 在返回 false 后停止添加的事件侦听器函数
- 如果if语句中的Javascript函数应该为true,则该函数返回false
- Javascript函数,当jQuery点击事件发生时返回true,否则返回false
- 为什么Internet Explorer在使用event.prventDefault()或返回false时在函数后停止
- 为什么原型中的javascript函数返回true或false