Reset the last setTimeout in React [duplicate]

  javascript, reactjs, settimeout

If I submit more than 1 item within 4 seconds here, I want to submit only the final item and cancel the others. How can I clear the other timeouts and keep only the last one? I tried the following,

submit handler:

   const submitTodoHandler = (e) => {
     e.preventDefault();
     if (inputText === "") {
       alert("Cannot add Empty Strings");
      } else if (todos.length + 1 > 5) {
        alert("Cannot add more than 5 items");
      } else {
        setUploadingStatus(true);
        clearTimeout(timer);
        timer();        
    }
  };

timer:

timer = () => setTimeout(() => {
  console.log("hahaha")
  setUploadingStatus(false);
  setInputText("");

  clearTimeout(timer);
  
  setTodos((prevTodos) => {
    const newTodoState = {
      text: inputText,
      completed: false,
      id: Math.random() * 1000,
    };
    return [newTodoState, ...prevTodos];
  });
}, 4000);  

Source: Ask Javascript Questions

LEAVE A COMMENT