To ensure that your event handler functions are not called multiple times for the same event, it is recommended to implement a debounce function. This function involves setting a timer and keeping track of how many times the event has occurred within a specific time frame.
One approach is to create a helper function that manages the delayed execution of your three event handler functions.
const debounceKeyPress = (keyCode, ...fns) => {
let noOfOccurrences = -1;
let timeout;
return (ev) => {
if (ev.keyCode !== keyCode) {
return;
}
noOfOccurrences += 1;
clearTimeout(timeout);
if (fns[noOfOccurrences]) {
timeout = setTimeout(() => { fns[noOfOccurrences](ev); noOfOccurrences = -1; }, 500);
}
}
}
This function accepts a key code and any number of functions, providing flexibility in the number of functions passed. The returned function can then be used as an event listener.
const fn1 = (ev) => console.log(`key ${ev.keyCode} was hit once.`);
const fn2 = (ev) => console.log(`key ${ev.keyCode} was hit twice.`);
const fn3 = (ev) => console.log(`key ${ev.keyCode} was hit three times.`);
document.addEventListener('keydown', debounceKeyPress(32, fn1, fn2, fn3));
You can adjust the timing parameter in the setTimeout function to determine the optimal delay for your specific use case. Additionally, you can include this parameter as an argument in the debounceKeyPress function for more customization options.
Feel free to experiment with different settings to find the best solution for your needs.
Best regards,
A.