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!

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more