DEV Community

Ayowande Oluwatosin
Ayowande Oluwatosin

Posted on

Creating a Countdown Timer with Vue.js

Service Level Agreements (SLAs) often come with strict timelines, and having a visual representation of the time remaining can be crucial. In this post, we'll explore how to implement a countdown timer in Vue.js to display the remaining time for SLAs.

Step 1: Set Up Your Vue Component

<template>
  <div>
    <span v-if="sla.expired" style="color: red;">{{ `SLA Expired` }}</span>
    <span v-else style="color: rgb(80, 180, 80)">{{ `${displayTime}` }}</span>
  </div>
</template>

<script>
import moment from 'moment';

export default {
  props: {
    sla: Object,
    created_at: String,
  },
  data() {
    return {
      intervalId: null,
      displayTime: '',
    };
  },
  mounted() {
    this.startCountdown();
  },
  beforeDestroy() {
    clearInterval(this.intervalId);
  },
  methods: {
    startCountdown() {
      const initialDate = moment(this.created_at).add(this.sla.time, 'hours');

      this.intervalId = setInterval(() => {
        const countdownDuration = initialDate.diff(moment());
        let secondsRemaining = moment.duration(countdownDuration).asSeconds();

        const hours = Math.floor(secondsRemaining / 3600);
        const minutes = Math.floor((secondsRemaining % 3600) / 60);
        const seconds = Math.floor(secondsRemaining % 60);

        this.displayTime = `${hours > 0 ? hours + 'h ' : ''}${minutes}m ${seconds}s`;

        if (secondsRemaining <= 0) {
          clearInterval(this.intervalId);
          this.$set(this.sla, 'expired', true);
        }

        secondsRemaining--;
      }, 1000);
    },
  },
};
</script>

<style scoped>
</style>
Enter fullscreen mode Exit fullscreen mode

We use the mounted lifecycle hook to initiate the countdown when the component is mounted.
The beforeDestroy hook ensures that the interval is cleared to prevent memory leaks when the component is destroyed.
The startCountdown method calculates the remaining time and updates the displayTime variable accordingly.
The countdown is displayed dynamically, and when it reaches zero, the SLA is marked as expired.

Step 2: Use the Countdown Timer Component

<template>
  <ul>
    <li v-for="(sla, j) in liquidasset.slas" :key="sla.id">
      <CountdownTimer :sla="sla" :created_at="liquidasset.created_at" />
    </li>
  </ul>
</template>

<script>
import CountdownTimer from '@/components/CountdownTimer.vue'; // Update the path based on your project structure

export default {
  components: {
    CountdownTimer,
  },
  data() {
    return {
      liquidasset: {
        created_at: '2024-01-27T12:00:00', // Example date
        slas: [...], // Your SLAs array
      },
    };
  },
};
</script>
Enter fullscreen mode Exit fullscreen mode

Conclusion
Implementing a countdown timer in Vue.js can enhance the user experience, especially in scenarios where time is of the essence. By breaking down the logic into a reusable component, you can easily integrate countdown timers into various parts of your application.

Feel free to customize the code further based on your specific requirements and styling preferences. Happy coding!

Top comments (0)