Method 1: Using a flag variable to check the current key status: A flag variable is defined which keeps track of the current key press. The ‘keyup’ and ‘keydown’ events are both set to modify this flag variable so that it correctly reflects the current status of the key press.
The ‘keydown’ event only allows for the respective event to fire if the key is not already held down by checking the flag variable. The ‘keyup’ event on the other hand sets the flag variable to indicate that the key has been released. Using both these with event listeners, one can make sure that the key fires only once even if it is being held down.
Method 2: Using the repeat property: The ‘repeat’ property of the KeyboardEvent interface is used to check if a key is getting repeated as a result of being held down by the user. This property can be checked on every ‘keydown’ event and allow the specified event to only fire if it returns false. This prevents the key from firing multiple times even if the user holds the key down.