I wanted to detect when a user stops typing. I encountered this answer from SO (Not the selected answer, but the second one which seem to be better):
https://stackoverflow.com/a/5926782/17746636
But I edited it slightly to use keydown
instead of keyup
. Also the target is window
for my example (I need to detect any key strokes on the window):
let typingTimer;
let doneTypingInterval = 1000;
window.addEventListener('keydown', () => {
clearTimeout(typingTimer);
typingTimer = setTimeout(doneTyping, doneTypingInterval);
});
function doneTyping() {
console.log("Stopped typing");
}
I changed from keyup
to keydown
because there might be cases where a user can click on another window while typing, and then the timeout will never be released. Using keydown
seem to work better and ensures that if a user is typing and then clicks on another window, then it will trigger the doneTyping
function