Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS Function self-disable for a specific time after execution

Tags:

javascript

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?

like image 612
Wiktor Kisielewski Avatar asked Feb 03 '26 10:02

Wiktor Kisielewski


1 Answers

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.

like image 167
dquijada Avatar answered Feb 04 '26 22:02

dquijada



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!