I am trying to disable a function in JavaScript so that it only can be called once every 300ms.
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