Методы сброса таймера обратного отсчета с использованием JavaScript

Чтобы сбросить таймер обратного отсчета с помощью JavaScript, вы можете использовать различные методы. Вот несколько примеров:

Метод 1: использование setInterval()

// Set the initial countdown time
let countdownTime = 10;
// Create a function to update the countdown timer
function updateTimer() {
  countdownTime--;
  console.log(countdownTime);
  if (countdownTime === 0) {
    clearInterval(timer);
    console.log("Countdown timer reset");
  }
}
// Create an interval timer
let timer = setInterval(updateTimer, 1000);
// To reset the countdown timer, you can simply call clearInterval(timer)

Метод 2: рекурсивное использование setTimeout()

// Set the initial countdown time
let countdownTime = 10;
// Create a function to update the countdown timer
function updateTimer() {
  countdownTime--;
  console.log(countdownTime);
  if (countdownTime > 0) {
    setTimeout(updateTimer, 1000);
  } else {
    console.log("Countdown timer reset");
  }
}
// Initialize the countdown timer
updateTimer();
// To reset the countdown timer, you can stop the recursion by not calling setTimeout(updateTimer, 1000)

Метод 3. Использование обещаний

// Create a function to start the countdown timer
function startCountdown(duration) {
  return new Promise((resolve, reject) => {
    let countdownTime = duration;
    let timer = setInterval(() => {
      countdownTime--;
      console.log(countdownTime);
      if (countdownTime === 0) {
        clearInterval(timer);
        resolve();
      }
    }, 1000);
  });
}
// Usage:
startCountdown(10)
  .then(() => {
    console.log("Countdown timer reset");
  })
  .catch((error) => {
    console.error(error);
  });
// To reset the countdown timer, you can simply call startCountdown(10) again