Javascript—如果满足条件,则在特定时间内返回True,然后返回false
我试图编写一个函数,如果满足某些条件,它将在一段时间内返回“true”,然后再次返回false,即使条件仍然为true 代码的思想是这样的:Javascript—如果满足条件,则在特定时间内返回True,然后返回false,javascript,function,if-statement,timer,Javascript,Function,If Statement,Timer,我试图编写一个函数,如果满足某些条件,它将在一段时间内返回“true”,然后再次返回false,即使条件仍然为true 代码的思想是这样的: if(condition is met) {return 'True' for 3000ms then 'false'} //even if the condition it's still 'true' else {False} 我可以很容易地对条件的结果进行编程(如果满足,则返回true或false),但是我在尝试(如果为tr
if(condition is met)
{return 'True' for 3000ms then 'false'} //even if the condition it's still 'true'
else {False}
我可以很容易地对条件的结果进行编程(如果满足,则返回true或false),但是我在尝试(如果为true)在特定时间内返回它时遇到了很多困难
注意:在这种情况下,带有setTimeout()的函数不是选项
谢谢 您可以在此场景中使用闭包
function falseReturnAfter(time) {
let val = true;
setTimeout(() => {
val = false;
}, time);
return function(con) {
if(con && val) {
return true;
}
return false;
}
}
let f = falseReturnAfter(10000) // return false after 10 sec.
f(true) // true
f(false) // false
// after 10 sec
f(true) // false
f(false) // false
也许这会对你有所帮助。听起来像。你想用这个来解决什么问题?@kavigun确实如此-在时间结束后执行返回的函数将翻转结果。