Search code examples
javascriptjquerykeystroke

Differentiate between key pressed and key held


I have a javascript function which runs when the 'down' key is pressed. I would like, that if the 'down' key is held down, the function would not run at all.

I thought about timing between keydown and keyup, if the time is less than 1 second then the function would run on keyup. The problem is, if I hold the key down the browser sees it as the key being pressed many times in succession.

Is there a better way to do this?

Thanks


Solution

  • If I understand your problem is that your browser interprets a key being held as multiple keydown events. You want something different to happen if a key is held versus when it's simply pressed; and you want that difference to be based on some time which you think should constitute "holding" the key. So you need to differentiate between a hold and a press by tracking the keyup event. The following pseudocode will resolve this problem:

    On Keydown:

    if !yourBool 
        start timer
    
    yourBool = true 
    

    on Keyup:

    if timer < yourTime
        do something
    
    yourBool = false
    

    This will work because the timer will not restart unless keyup event has occurred.

    Now... if your browser interprets key holding as:
    Keydown, Keyup, Keydown, Keyup.......
    then you have a problem with this approach.