简体   繁体   English

如何临时禁用JavaScript中的功能?

[英]How to disable a function temporarily in JavaScript?

I am trying to disable a function in JavaScript so that it only can be called once every 300ms. 我试图禁用JavaScript中的功能,以便每300毫秒只能调用一次。

To do this, I guessed the best approach would be to do sth like this: 为此,我猜测最好的方法是这样做:

var locked = (function () {
    var lock = null;
    return function () {
        if (lock != null)
            return false;

        lock = setTimeout(function () {
            lock = null;
        }, 300);
        return true;
    };
})();

And use this lock in other functions like this: 并在其他类似功能中使用此锁:

function superImportantFunction() {
    if(locked()) return;
}

Now, this does not work for some reason. 现在,由于某种原因,这不起作用。 Do you have any better suggestions or maybe a reason why the code does not work? 您是否有更好的建议,或者是代码无法正常工作的原因?

Thanks! 谢谢!

how does it not work? 它怎么不起作用? Seems to work for me. 似乎为我工作。 Although you probably need to create separate locks for different functions unless you want them to share the lock. 尽管您可能需要为不同的功能创建单独的锁,除非您希望它们共享锁。 And you need to reverse your return values. 而且您需要反转您的返回值。

edit reversing the boolean 编辑反转布尔值

var lockF = function () {
    var lock = null;
    return function () {
        if (lock != null)
            return true;

        lock = setTimeout(function () {
            lock = null;
        }, 300);
        return false;
    };
}; 
var func1locked = lockF();

var func2locked = lockF();

In

var lock = null;
return function () {
    if (lock != null)
        return false;

you are setting lock to null and then checking if lock is not equal to null. 您将lock设置为null,然后检查lock是否不等于null。 That is, your return function will always return false. 也就是说,您的return函数将始终返回false。

Try moving your lock declaration out of the Locked() function: 尝试将锁声明移出Locked()函数:

var lock = null;
var locked = (function () {    
return function () {
    if (lock != null)
        return false;

    lock = setTimeout(function () {
        lock = null;
    }, 300);
    return true;
};
})();

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

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