Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid holding key triggering multiple events?

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.

like image 764
Eloi Avatar asked Sep 05 '25 03:09

Eloi


1 Answers

you can use the event.repeat to check if the key is already been pressed

https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/repeat

window.addEventListener('keydown', (e) => {
            
            if (e.repeat) return;

              //your code 
            switch (e.key) {
              
                case 'ArrowLeft':
                    console.log('left');
                    break;
                case 'ArrowRight':
                    console.log('right');
                    break;
            }
        });
like image 169
Andrew Nic Avatar answered Sep 07 '25 23:09

Andrew Nic