skip to Main Content

I have this cool typing effect on my site that executes when you press enter but I do not want users to be able to press enter again while the typing effect is executing.
This is what I am currently working with:

document.addEventListener("keyup", function(event) {
    if (event.key === 'Enter') {
        getResult(document.getElementById("input").value)
    }
});

I have tried removing the event listener within itself but then how would I add it back?

2

Answers


  1. Chosen as BEST ANSWER

    I just ended up making bool that is set to false and is true when you press enter for the first time. Then the bool is reset to the false state when the event is concluding. I do not think it is the most elegant option but it works nicely.

    document.addEventListener("keyup", function(event) {
        if (event.key === 'Enter' && writing === false) {
            writing = true;
            getResult(document.getElementById("input").value);
            window.onkeydown = speedUp;
        }
    });
    

  2. That depends on the typing effect duration, but lets assume it takes 400ms. So what you would want is called to throttle the function calls. This is nicely done by first generating a throttled version of the event handler.

    This one is from https://www.geeksforgeeks.org/javascript-throttling/

    const throttleFunction = (func, delay) => {
      let prev = 0;
      return (...args) => {
        let now = new Date().getTime();
        if (now - prev > delay) {
          prev = now;
          return func(...args);
        }
      }
    }
    

    Update: I will not be using it, but instead will use the very same idea inside the event handler, thus effectively "disconnecting" it from functioning.

    let prev = 0
    let delay = 400
    document.addEventListener("keyup", function(event) {
      if (event.key === 'Enter') {
        let now = new Date().getTime();
        if (now - prev > delay) {
          prev = now;
          getResult()
        } else {
          console.log("... wait ...")
        }
      }
    });
    
    
    function getResult() {
      console.log("registered");
    }
    press [Enter] a few times, fast
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search