Somehow my same closed ,because the question was not clear to everyone.
I a repeating the same question.
Here i have this input field when the user is typing I am calling handleMessagePress(e) function continuously ,and when the user stops typing I, am calling stop() function after five seconds . But my question is when the user starts typing , i need to call handleMessagePress(e) function only once and wait for 5 seconds and if the user is still typing the same function should be called automatically otherwise the stop function should be called automatically. In simpler words after 5seconds my Program should be able to check user is typing or not whether the user is typing or not if typing call handleMessagePress(e) otherwise call stop function automatically
<input placeholder="type your message" id="messageInputField" onKeyPress={(e) => handleMessagePress(e)}/>
let myInput = document.getElementById("messageInputField");
let timer;
if (myInput) {
myInput.addEventListener("keyup", () => {
clearTimeout(timer);
timer = setTimeout(stop, 5000);
});
}
const stop=()=>{
console.log("user stop typing");
}
const handleMessagePress = (e) => {
console.log("user is typing");
}
let myInput = document.getElementById("messageInputField");
let timer;
let executeHandlePress = true; // flag to watch handle press function execution
if (myInput) {
myInput.addEventListener("keyup", () => {
clearTimeout(timer);
timer = setTimeout(stop, 5000);
});
}
const stop=()=>{
console.log("user stop typing");
}
const handleMessagePress = (e) => {
if(!executeHandlePress){ // if flag false, return
return;
}
console.log("user is typing"); // if true execute
executeHandlePress = false; // toggle flag to false
setTimeout(()=>{
executeHandlePress = true; // reset after 5 seconds
}, 5000);
}
<input placeholder="type your message" id="messageInputField" onKeyPress=" handleMessagePress(event)" />