Reputation: 437
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?
Upvotes: 3
Views: 1757
Reputation: 1699
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.
Upvotes: 4
Reputation: 15821
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();
}
}
Upvotes: 2
Reputation: 681
Some thing like that, execution will be disable for 5s
var lastClicked = 0;
document.onkeypress = function(e) {
var now = new Date();
if (now - lastClicked > 5000) { //set a 5s delay
lastClicked = now;
if (e.keyCode == '32') {
do_something();
}
}
}
function do_something() {
console.log('lorem ipsum');
}
Upvotes: 0
Reputation: 495
var timeout = false; //Control variable
var miliseconds = 2000; //Time in miliseconds for the function to enable again
function do_something() {
if(timeout) return alert("Function disabled");
console.log('lorem ipsum');
timeout = true;
setTimeout(function() { timeout = false }, miliseconds);
}
document.onkeypress = function(e) {
if (e.keyCode == '32') {
do_something();
}
}
Upvotes: -1
Reputation: 1349
A very silly answer would be to sleep javascript execution for a specific time.
function sleep(delay) {
var start = new Date().getTime();
while (new Date().getTime() < start + delay);
}
Then
document.onkeypress = function(e) {
if (e.keyCode == '32') {
do_something();
sleep(2000);
}
}
I said silly
because it stop your entire script for a specific time, you may not need that behavior!
Upvotes: 0