In a current project I`m making, I have a timer which accepts values in format "00:00:00" or "hours:minutes:seconds" in an input field and a button which converts the formats to "00:00:00" if neccessery, and starts incrementing the time on the timer. I want to make it so a "CheckInput()" function runs as soon as the user stops typing in the input field before he even presses the start button. I want this to be pure JavaScript without frameworks if possible.
"OnMouse" events will not work in this case, I thought about checking for "onkeydown" events between an interval of about 0,2-0,5 s and if there are none to assume the user has stopped typing, but can`t seem to figure out how to implement it correctly.
Vanilla js solution, assuming the stopping time is 2 seconds
//setup before functions
let typingTimer; //timer identifier
let doneTypingInterval = 2000; //time in ms (2 seconds)
let myInput = document.getElementById('myInput');
//on keyup, start the countdown
myInput.addEventListener('keyup', () => {
clearTimeout(typingTimer);
if (myInput.value) {
typingTimer = setTimeout(doneTyping, doneTypingInterval);
}
});
//user is "finished typing," do something
function doneTyping () {
//do something
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.