Search code examples
javascripthtmladdeventlistener

function to clear the input value by newly input value after delay is not working


I'm trying to make a function that clears the input value by the new text I type after a 2-second delay.

At first it worked, but now for some reason, it just replaces the value of the input by the first letter of the word I typed before the delay.

Sometimes it removes the containers below the input as well.

Here is the code if you want to try for yourself :

https://codepen.io/Hautzii/pen/gOEWqjV

input.addEventListener('input', (e) => {
  if (inputPause) { e.target.value = e.target.value.charAt(0); inputPause = false;}
  if (timeOut) clearTimeout(timeOut)
  timeOut = setTimeout(() => { inputPause = true }, 2000)
})

Solution

  • I added logic to the setTimeout statement to fit your needs. The current input will be cleared for your new input after 2s.

    EDIT: The code will now split the event target value and get the last element of it (your last input).

    input.addEventListener('input', (e) => {
      if (inputPause) { 
        e.target.value = e.target.value.split('').slice(-1);
        inputPause = false;
      }
      if (timeOut) clearTimeout(timeOut)
      timeOut = setTimeout(() => { inputPause = true }, 2000)
    })