0

I'm trying to execute a function once while there are many times a single event listener is repeating, I'm building a text-to-speech app, and I'm trying critical event listeners but the app generates voice again and again on every single event, I did with start/stop button it works, but I want to speak automatically after 1 or 0.5 seconds when we type something in textarea

document.querySelector("textarea").addEventListener("keyup", async e => {
    let executed = false;
    speech.text = document.querySelector("textarea").value;
    if (!executed) {
      executed = true;
      window.speechSynthesis.speak(speech);
    } else {
      console.log("executed");
    }
  });

I tried to complete using Booleans but not worked

SAKSoomro
  • 25
  • 6

2 Answers2

0

You're resetting executed on every event trigger.

let isExecuted = false;

const debounce = (func, delay) => {
  let debounceTimer
  return function() {
    const context = this
    const args = arguments
    clearTimeout(debounceTimer)
    debounceTimer
      = setTimeout(() => func.apply(context, args), delay)
  }
}

document.querySelector("textarea").addEventListener("keyup", async(_event) => {
  speech.text = _event.target.value;

  if (!isExecuted) {
    isExecuted = true;
    debounce(window.speechSynthesis.speak(speech), 1500);
  } else {
    console.log("already executed");
  }
});
Aahan Agarwal
  • 391
  • 2
  • 6
0
    function oneTimeFunction(e){
       speech.text = document.querySelector("textarea").value;
       window.speechSynthesis.speak(speech);
       console.log("executed");
       e.target.removeEventListener(
          e.type, //indicate event type - here the same as fired
          oneTimeFunction //which function to remove from certain listener
       )
    }
    document.querySelector("textarea").addEventListener("keyup", oneTimeFunction );

So that function removes itself from target element after executng it's body. Hence it actually detects which type of event it was subscribed so addEventListener is quite readable.

I hopoe it's most easy way to provide and to uderstand. To remove some listener You need to know event name and function name, so You have to define function what i did.

Bujaq
  • 69
  • 6