0

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");
    }
2
  • So in plain english: Once a user starts typing, every 5 seconds, you want to check if the user is still typing or has stopped typing? Commented Sep 22, 2021 at 13:28
  • Husman: yes it's like that Commented Sep 22, 2021 at 13:33

1 Answer 1

2

 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)" />

Sign up to request clarification or add additional context in comments.

4 Comments

Alaksandar Jesus Gene: It's not calling stop function
Can you please paste sandbox link here
click on Run Code Snippet prnt.sc/1t8kyi0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.