albert_anthony6
albert_anthony6

Reputation: 614

Vue clear interval beforeDestroy

I have a countdown timer on a component which works well. The problem is that I want the interval to stop once the user leaves the component's page. I'm trying to clearInterval in the beforeDestroy hook but for some reason, I still get errors every one second from the interval and that it can't find IDs of null. These errors only happen once the component has been destroyed.

<template>
  <div class="countdown">
    <img class="cover-image" src="@/assets/img/[email protected]" />
    <div class="countdown-container">
      <h2>Countdown to placeholder:</h2>
      <div class="counter">
        <div>
          <div id="day">0</div>
          Days
        </div>
        <div>
          <div id="hour">0</div>
          Hours
        </div>
        <div>
          <div id="minute">0</div>
          Minutes
        </div>
        <div>
          <div id="second">0</div>
          Seconds
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'Countdown',
  data() {
    return {
      countDate: new Date('Jan 1, 2021 00:00:00:00').getTime(),
      counter: null,
    };
  },
  beforeCreate() {
    this.counter = setInterval(() => {
      const now = new Date().getTime();
      const gap = this.countDate - now;

      const second = 1000;
      const minute = second * 60;
      const hour = minute * 60;
      const day = hour * 24;

      let d = Math.floor(gap / day);
      let h = Math.floor((gap % day) / hour);
      let m = Math.floor((gap % hour) / minute);
      let s = Math.floor((gap % minute) / second);

      if (d <= 0 && h <= 0 && m <= 0 && s <= 0) {
        clearInterval(this.counter);
        d = 0;
        h = 0;
        m = 0;
        s = 0;
      }
      document.querySelector('#day').innerText = d;
      document.querySelector('#hour').innerText = h;
      document.querySelector('#minute').innerText = m;
      document.querySelector('#second').innerText = s;
    }, 1000);
  },
  beforeDestroy() {
    clearInterval(this.counter);
  },
};
</script>

Upvotes: 1

Views: 2028

Answers (1)

Tony
Tony

Reputation: 1432

I believe the error is coming from the beforeCreate hook. In the beforeCreate hook, the component is not available in the DOM.

Trying moving the logic in the beforeCreate hook to the mounted hook, which is called when the component is mounted in the DOM.

Upvotes: 2

Related Questions