How to avoid holding key triggering multiple events (JS)

Viewed 228

I'm trying to create this event to navigate through the website with arrow keys. The problem that I'm facing is that if someone holds one of the keys, the function (in this case console.log) will trigger repeatedly which may cause some undesirable behaviour with complex functions.

I want console.log to be triggered only once for each keydown.

window.addEventListener('keydown', function (e) {
    switch (e.key) {
        case 'ArrowLeft':
            console.log('left');
            break;
        case 'ArrowRight':
            console.log('right');
            break;
    }
});

I ended up using this:

let allowKey = true;

window.addEventListener('keydown', function (e) {
    switch (e.key) {
        case 'ArrowLeft':
            if (allowKey) {
                console.log('Left');
                allowKey = false;
            }
            break;
        case 'ArrowRight':
            if (allowKey) {
                console.log('Right');
                allowKey = false;
            }
            break;
    }
});
window.addEventListener('keyup', function(e) {
    switch (e.key) {
        case 'ArrowLeft':
            allowKey = true;
            break;
        case 'ArrowRight':
            allowKey = true;
            break;
    }
});

Thank you.

3 Answers

You could make a variable that checks if the key went up. Like this:

var isKeyDown = false;

window.addEventListener('keydown', function(e) {
    if (!isKeyDown) {
      isKeyDown = true;
    } else {
      return
    }
    switch (e.key) {
        case 'ArrowLeft':
            console.log('left');
            break;
        case 'ArrowRight':
            console.log('right');
            break;
    }
});

window.addEventListener('keyup', function(e) {
  isKeyDown = false;
});

change 'keydown' to 'keyup'. that will only run when the key is released, so its foolproof. Like so:

window.addEventListener('keyup', function(e) {
            switch (e.key) {
                case 'ArrowLeft':
                    console.log('left');
                    break;
                case 'ArrowRight':
                    console.log('right');
                    break;
            }
        });
Related