I'm trying to create a function which is executed by a keypress and disabled for a specific time after execution.
function do_something() {
console.log('lorem ipsum');
}
document.onkeypress = function(e) {
if (e.keyCode == '32') {
do_something();
}
}
Is there any way to disable it for (let's say) 2 seconds after every execution?
Yes, there is a way: use a Timeout to temporally set a boolean to certain value and then check it's value before calling do_something().
Example:
let cooldown = false;
const RECHARGE_TIME = 2000; //ms
function do_something() {
console.log('lorem ipsum');
}
document.onkeypress = function(e) {
if (!cooldown && e.keyCode == '32') {
do_something();
startCooldown();
}
}
function startCooldown() {
cooldown = true;
setTimeout (function(){ cooldown = false}, RECHARGE_TIME);
}
EDIT: as Mosè Raguzzini noted: Depending on how important accuracy is, maybe this isn't the best method, since (as you can see here) it can be inacurate.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With