JS Function self-disable for a specific time after execution

Wiktor Kisielewski

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?

Mosè Raguzzini

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.

edited at
0

Comments

0 comments
Login to comment

Related

how to disable login after specific period of time

Return for function after certain execution time

disable button in specific time using js

Node JS function undefined after execution

How to close a bat after a specific time without intrerupting the execution?

Batch file execution with closing automatically after a specific period of time

Javascript: Call a function after specific time period

Calling a function after a specific time, inside a loop

how to fire a function after hovering for a specific time?

Receive print content of another class at execution time not after the end of the function

Call a js url after specific time (Seconds)

Function execution time

Measure the execution time of a function

JavaScript function execution time

Disable function for a period of time after its launched to wait animation to complete

Limit execution time of await dns reverse function js

node.js mocha before function runs after test execution

Need third async function to execute after the execution of first two in js?

How to run a function after specific time then switch it off after specific time?

VisualVM java profiling - self time execution?

Add redirection when button is clicked first time then disable it for specific time even after page reload using jQuery

Stop jQuery execution after one time execution

Gradle disable automatic subproject execution for specific task

Node js, function execution

JS multiple function execution

Trying to delay a specific function for spawning enemy after a certain amount of time

Why is execution time of this function increasing?

Tracking function execution time with jasmine

Node js returning specific time to setInterval after break