Running Functions on a Held Keypress

Recently, I was making an app which required me fire a function after the user held down the command/ctrl key for a set period of time. The function was not supposed to fire if they released the key before that time period was up. At first, I figured this would be one of the simplest parts of my code. I was already using jQuery in other parts of my app so I thought I would just use the .keydown() or .keyup() functions that are built in and throw in a setTimeout() to wrap it all up. I quickly found that it wasn’t actually that easy.

The jQuery keypress functions run as soon as the event is fired. As I said earlier, this is much more difficult to solve than just simply waiting for a certain amount of time. If you use setTimeout on a keypress event listener, the function will still run even if the user lifts his finger off the key before the time is up. It will just run a bit later than it would have without the setTimeout.

How to solve the problem

Our problem can be solved using two event listening functions. The first one, listens for the keydown and sets the switch variable, in our case ‘keydown’, to true. The variable keydown outside the function is what we will use to escape the function if necessary.

var keydown = false;
var timer;
$(window).keydown(function(event) {
if (event.keyCode === 91 || event.keyCode === 93) keydown = true;
timer = setTimeout(function() {
if (keydown) {
//Do stuff
}, 700);

The second function checks whether the user has lifted his or her finger off of the key before the time has allotted. If they have, we set keydown to false and escape.

$(window).keyup(function(event) {
if (event.keyCode === 91 || event.keyCode === 93) {
keydown = false;

I hope this helps anyone who is trying to run something on a held down keypress