@LI4NOOST

Как остановить один интервал и начать другой?

const inputEl = document.querySelector('input');
const buttonEl = document.querySelector('button');
const timerEl = document.querySelector('span');
timerEl.textContent = '00' + (' : ') + '00' + (' : ') + '00'


const createTimerAnimator = () => {
    return (time) => {
      const visibleResult =()=>{
          const formatter = Intl.NumberFormat(undefined, {
              minimumIntegerDigits: 2
          });
          const hours = formatter.format ( Math.floor(time / 60 / 60) )
          const minutes = formatter.format( Math.floor(time / 60) - (hours * 60) )
          const seconds = formatter.format ( time % 60 )
          timerEl.textContent = `${hours} : ${minutes} : ${seconds}`
      }
      visibleResult()

      const animate= setInterval(()=>{
           if (time > 0){
               visibleResult(time --)
           }else {
               clearInterval(animate)
           }
       }, 1000)

    };
};


const animateTimer = createTimerAnimator();

inputEl.addEventListener('input', () => {
    inputEl.value = inputEl.value.replace(/\D/g, '')
});

buttonEl.addEventListener('click', () => {
    const seconds = Number(inputEl.value);
    animateTimer(seconds);
    inputEl.value = '';
});

Есть таймер обратного отсчета, при изменении значения time, прошлый интервал продолжает работать. То есть отсчитывается первое значение time и следующее. Соответственно таймеры начинают мелкать. Подскажите, как сбросить значение старого интервала?
  • Вопрос задан
  • 50 просмотров
Решения вопроса 1
modelair
@modelair
unsocial
const createTimerAnimator = () => {
  let intervalId
  return (time) => {
    if (intervalId) clearInterval(intervalId)
    const visibleResult = () => {
      const formatter = Intl.NumberFormat(undefined, {
        minimumIntegerDigits: 2
      })
      const hours = formatter.format(Math.floor(time / 60 / 60))
      const minutes = formatter.format(Math.floor(time / 60) - (hours * 60))
      const seconds = formatter.format(time % 60)
      timerEl.textContent = `${hours} : ${minutes} : ${seconds}`
    }
    visibleResult()

    intervalId = setInterval(() => {
      if (time > 0) {
        visibleResult(time--)
      } else {
        clearInterval(intervalId)
      }
    }, 1000)

  }
}
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы
04 мая 2024, в 06:10
4000 руб./за проект
04 мая 2024, в 05:49
10000 руб./за проект
04 мая 2024, в 03:57
10000 руб./за проект