简体   繁体   English

Javascript - 如果满足条件,则在特定时间内返回 True,然后返回 false

[英]Javascript - If condition is met, return True for specific amount of time, then false

I'm trying to code a function that, if some conditions are met, it returns "true" for some time, then return false again, even if the condition is still true.我正在尝试编写一个函数,如果满足某些条件,它会在一段时间内返回“真”,然后再次返回假,即使条件仍然为真。

The idea of the code is something like this:代码的想法是这样的:

if(condition is met)
    {return 'True' for 3000ms then 'false'} //even if the condition it's still 'true'
        else {False}

I can easily program the result of the condition (returning true or false if met), but i'm having a lot trouble trying to (if true) returning it for a specific amount of time.我可以轻松地对条件的结果进行编程(如果满足则返回 true 或 false),但是我在尝试(如果为 true)在特定时间内返回它时遇到了很多麻烦。

NOTE: a function with setTimeout() is not an option in this case.注意:在这种情况下,带有 setTimeout() 的函数不是一个选项。

Thanks!谢谢!

You can use closure for this scenario您可以在这种情况下使用闭包

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

Maybe this will help you.也许这会帮助你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM