setInterval problems with a countdown timer using Draftbit

85 Views Asked by At

enter image description hereI have this set up to start a countdown timer...

const initialCountdown = 10; // Initial countdown value (change as needed)
let countdown = initialCountdown;

const intervalId = setInterval(() => {
  if (countdown > 0) {
    countdown--;
    setSeconds(countdown);
  } else {`your text`
    resetInterval(intervalId);
    countdown = initialCountdown;
    setSeconds(countdown);
  }
}, 1000);

function resetInterval(intervalId) {
  clearInterval(intervalId);
  // Perform any other reset operations here if needed
}

This starts the timer and resets it at 0

I need to stop it glitching when the start button is pressed twice and I need to add a stop/resume function to another button. I use draftbit which is a lowcode app app builder which allows custom code. i use an on press action for the button to start the timer (see attached). Ne to javaScript as you can probably tell ... Please help

I have tried several versions of the code and everything i have tried that is not the above totally breaks the timer

1

There are 1 best solutions below

10
On

Just test if it is running

const initialCountdown = 10; // Initial countdown value (change as needed)
let countdown = initialCountdown;
let intervalId;

function onPressHandler() {
  if (intervalId) return;
  let intervalId = setInterval(() => {
    if (countdown > 0) {
      countdown--;
      setSeconds(countdown);
    } else {
      resetInterval(intervalId);
      countdown = initialCountdown;
      setSeconds(countdown);
    }
  }, 1000);
}

function resetInterval(intervalId) {
  clearInterval(intervalId);
  // Perform any other reset operations here if needed
}