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?
Try that, is a very simple and straightforward solution:
var firstExecution = 0; // Store the first execution time
var interval = 2000; // 2 seconds
function do_something() {
// current date
var date = new Date();
var milliseconds = date.getTime();
if((milliseconds - firstExecution) > interval){
firstExecution = milliseconds;
console.log('lorem ipsum');
} else {
console.log('too early');
}
}
document.onkeypress = function(e) {
if (e.keyCode == '32') {
do_something();
}
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments