0

I got to evenListeners one to start the timer and one to stop it Is it possible to make the start one to work only once and then get disabled until the stop button is clicked ???

startButton.addEventListener("click", startTimer);
stopButton.addEventListener("click", function stopFunction() {})
sina_byn
  • 97
  • 8
  • 1
    https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/removeEventListener – Teemu Jan 23 '22 at 17:03
  • 1
    Does this answer your question? [How to stop a setInterval function on click, and restart after a few seconds](https://stackoverflow.com/questions/34179841/how-to-stop-a-setinterval-function-on-click-and-restart-after-a-few-seconds) – pilchard Jan 23 '22 at 17:08
  • also: [Why won't my countdown timer start and stop?](https://stackoverflow.com/questions/40638402/why-wont-my-countdown-timer-start-and-stop) and [Start and Stop timer not working](https://stackoverflow.com/questions/18237502/start-and-stop-timer-not-working) – pilchard Jan 23 '22 at 17:09

2 Answers2

3

Yes, you can just use removeEventListener

function startTimer() {
  // whatever code

  // Disable after use
  startButton.removeEventListern("click", startTimer);
}
startButton.addEventListener("click", startTimer);

// Reset listener after stop button clicked
stopButton.addEventListener("click", () => {
  startButton.removeEventListener("click", startTimer);
  startButton.addEventListener("click", startTimer);
});

Can also simplify with shorthand:

const disableBtn = () => startButton.removeEventListener("click", startTimer);
const enableBtn = () => (disableBtn(), startButton.addEventListener("click", startTimer));

function startTimer() {
  // whatever code
  disableBtn();
}
enableBtn();
stopButton.addEventListner("click", enableBtn);
skara9
  • 4,042
  • 1
  • 6
  • 21
0

by using the line below you can remove the listener.

 startbutton.removeEventListener("click", startTimer);

and if you want to handle it with another button just call a function on click.

function stopFunction() {
   startbutton.removeEventListener("click", startTimer);
});
Hadi R.
  • 403
  • 3
  • 12