DEV Community

Ayowande Oluwatosin
Ayowande Oluwatosin

Posted on

1

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!

Jetbrains image

Is Your CI/CD Server a Prime Target for Attack?

57% of organizations have suffered from a security incident related to DevOps toolchain exposures. It makes sense—CI/CD servers have access to source code, a highly valuable asset. Is yours secure? Check out nine practical tips to protect your CI/CD.

Learn more

Top comments (0)

Jetbrains image

Build Secure, Ship Fast

Discover best practices to secure CI/CD without slowing down your pipeline.

Read more

👋 Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay