InnerText flickering after setTimeout

Viewed 174

I'm working on a small project between school projects, and I'm having a problem with a DOM element where I use innerText to go from a clock to text, and then after 5s, I want to empty that text. Everything works but the text flicker after a while.

// Break Time // Break Time // Break Time // Break Time
let inputTime = document.getElementById('breakTimeInput');

document.querySelector('#cta-paus').addEventListener('click', function () {
  if (inputTime.value === '') {
    swal('Break Time', 'You forgot to set break time!', 'warning');
    return;
  }

  let breakTime = inputTime.value * 60;

  setInterval(updateCountdown, 1000);

  function updateCountdown() {
    let minutes = Math.floor(breakTime / 60);
    let seconds = breakTime % 60;

    // Adds zero infront of secunds
    seconds = seconds < 10 ? '0' + seconds : seconds;

    // Out puts the time
    document.querySelector(
      '#MyClockDisplayDown'
    ).innerText = `${minutes}:${seconds}`;
    breakTime--;

    // Removes zero when minutes are done
    if (minutes == 0) {
      document.querySelector('#MyClockDisplayDown').innerText = `${seconds}`;
    }

    // If the count down is finished, write some text
    if (breakTime < 0) {
      document.querySelector('#MyClockDisplayDown').innerText = 'On Air';
      inputTime.value = '';

      setTimeout(() => {
        document.querySelector('#MyClockDisplayDown').innerText = '';
      }, 2000);
    }
  }
});

1 Answers

You would need to call clearInterval when finished: the updateCountdown function is still called every second

Something like this?

...

document.querySelector('#cta-paus').addEventListener('click', function () {
  ...

  var intervalId = setInterval(updateCountdown, 1000);

  function updateCountdown() {
    ...

    // If the count down is finished, write some text
    if (breakTime < 0) {
      ...

      clearInterval(intervalId); // <=== Add this

      setTimeout(() => {
        document.querySelector('#MyClockDisplayDown').innerText = '';
      }, 2000);
    }
  }
Related