Home > OS >  How can I change the execution time of a method in JS triggered by pressing a key, while holding dow
How can I change the execution time of a method in JS triggered by pressing a key, while holding dow

Time:01-31

I have a JS Method which triggers when a key is pressed. If the key is "Up-Arrow" it would trigger another method. The thing is that if I press it once, everything is fine, but when I hold down the button, it would execute my method until I release the button and it would to it with a speed (like 10 times a second).

My question is how can I add a delay, similar to the delay in C, freezing the whole application for the given time? If there is another option, let me know as well. Here is also the simple method:

function checkKey(e) {
    e = e || window.event;
    if (e.keyCode == '38') {
        // up arrow
        myMethod();
    }
}

CodePudding user response:

you could try a semaphore variable which gets set on the first key hit and reset after a timeout. every following event of keypress is ignored until the semaphore is free again.

CodePudding user response:

You want setTimeout.

// a "function wrapping function" that creates a function which
// delays calls to specific functions when holding predefined keys
function delayKeydownBy(ms, keyFuncMap) {
  let t = null; // holds a timeout ID
  return function (event) { // this will be the event handler function
    let f = keyFuncMap[event.key]; // is the key defined/known?
    if (!t) { // if we do not have a pending timeout...
      if (f != null) { // ... and the key is known ...
        t = setTimeout( // ... create a new timeout ...
          () => {
            t = null; // ... that resets itself ...
            f(); // ... and calls the function ...
          },
          ms // ... after X milliseconds
        );
      }
    }
  }
}

// for demonstration purposes
function myMethodA() {
  window.console.log('Now A');
}

function myMethodB() {
  window.console.log('Now B');
}

// adds a global keydown listener
document.addEventListener('keydown', delayKeydownBy(500, {
  'a': myMethodA,
  'b': myMethodB
}))

Additional info: I suggest you use event.key instead of event.keyCode, because the latter is marked as deprecated for some time being. See MDN

  • Related