Vuejs Countdown Timer Powered by Moment.js

Currently, I am working on a vuejs page and I am looking to incorporate a countdown timer that counts down from 5 minutes (e.g. 5:00, 4:59, and so on). Although I have never used momentjs before, I have gone through the moment docs but I am finding it challenging to understand the implementation process. Any assistance from someone experienced in using momentjs would be greatly appreciated as I am still in the learning phase.

<template>
  <div>{{ time }}</div>
</template>
<script>
var moment = require("moment");
export default {
  data() {
    return {
      time: "",
    };
  },
  mounted() {},
  methods: {},
};
</script>

Answer №1

If you're looking for a simple solution, check out this hosted resource: https://codesandbox.io/s/so-countdown-vuejs-momentjs-96hdw?file=/src/App.vue

Learn how to create a countdown in Vuejs using momentjs

<template>
  <div>{{ formatedCountdown || 'countdown over' }}</div>
</template>

<script>
import * as moment from 'moment'
import 'moment-duration-format'

export default {
  data() {
    return {
      countdown: 300, // 5min
    }
  },
  mounted() {
    const stopCountdown = setInterval(() => {
      console.log('current countdown', this.countdown)
      this.countdown -= 1
      if (!this.countdown) clearInterval(stopCountdown)
    }, 1000)
  },
  computed: {
    formatedCountdown() {
      return moment.duration(this.countdown, 'seconds').format('m:ss')
    },
  },
}
</script>

Answer №2

 let interval = 1000;
  let targetTime = moment();
  targetTime.add(interval, "milliseconds");
  targetTime.add(10, "seconds");

  //set up timer to track time difference
  const timer = setInterval(() => {
    //calculate the difference between current time and target time
    const timeDiff = moment.duration(targetTime.diff(moment()));

    if (timeDiff < 0) {
      clearInterval(timer);
      this.status = "none";
    }

    //format time difference to minutes:seconds
    this.timeRemainingToEnd = moment.utc(timeDiff.asMilliseconds());
  }, interval);

Remember to include the interval timer to ensure accuracy

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Discovering a way to monitor keyup and keydown occurrences in JavaScript on an iPhone

Looking to track keyup/keydown events in JavaScript on iPhone browsers. My goal is to automatically move the focus to the next form element after the user has inputted the maximum number of characters in a text box. ...

Configuring webpack: Eliminate hash in the file names of entry/bundle *.js files

I'm currently working on a Vue.js app. However, after building it, instead of getting the "background.js" file, I end up with "background.2a548437.js". To configure webpack-chain, I am using the "vue.config.js" file. While inspecting the results of ...

Storing data from multiple children and triggering a parent component function in Vue: A guide

In my Messaging Tool component, I have several child components that make up the messaging tool interface. You can see the visual representation of these components here: https://i.stack.imgur.com/JoEko.png There are 3 channels within the tool, each openi ...

Exploring ways to access data stored in interconnected models, such as MongoDB and NodeJS

As a newcomer to querying, I attempted a unique exercise to practice but unfortunately did not achieve the desired outcome. I have three models: const userSchema = new Schema({ info1: String, info2: String }, const serviceSchema = new Schema( { name ...

Retrieving the hidden field value using JavaScript on the server side

I'm encountering an issue with asp:hiddenfield where, after changing its value on the client side and trying to retrieve it on the server side, it returns null. Here is my client-side code: function pageLoad() { var gV = $('#<%=Hidden ...

Access information from Google Sheets through an AJAX GET request

I am facing an issue with my code while trying to retrieve data from a Google spreadsheet that I have already published. I have set the share properties of the spreadsheet to 'anyone can edit' and provided the correct URL, but I am still encounte ...

Combining both AJAX variables and HTML classes

Having trouble combining two AJAX variables with JQuery and PHP to add to a MySQL database... Here is the code snippet: $.ajax({ url: DIR+"some.php", method: "POST", dataType: "JSON", data: { mobile: mobile.val(), d ...

Receive an HTTP POST request within JavaScript without using Ajax in Symfony 4.1

Searching for a way to handle an event triggered by a PHP post, not through Ajax. I would like to show a spinner when the form is posted using PHP. In JavaScript, it's easy with code like this: $(document).on({ ajaxStart: function() { $('#p ...

Implementing a Response to an AJAX POST Request with Servlets

I have a unique situation where I need to validate a username input in a text box. The process involves sending the entered username to a server for checking if it has already been taken by another user. If the username is available, I want to change the b ...

What is the regular expression that allows numbers between 1 and 24, including decimals?

Can anyone help me create a regex expression that only allows numbers between 1 and 24, with up to 2 decimal places? The numbers should range from 1 to 24, as well as include decimals like 1.00, 1.01, 1.02, all the way up to 24.99. ...

Stop unauthorized access to php files when submitting a contact form

I have implemented a contact form on my HTML page that sends an email via a PHP script upon submission. However, when the form is submitted, the PHP script opens in a new page instead of staying on the current page where the form resides. I have tried usin ...

AngularJS Partial Views: Enhancing Your Website's User Experience

As a newcomer to the world of Angular, I am seeking guidance on a specific issue. I have encountered a one-to-many relationship scenario where one Category can have multiple Product items. The challenge lies in my layout page setup where I display various ...

jQuery failing to trigger onClick event for a specific group of buttons

Javascript: <script> $(document).ready(function(){//Implementing AJAX functionality $(".acceptorbutton").on('click', function(){ var whichClicked = this.attr('name'); ...

Updating an AngularJS directive following a service method invocation

My goal is to set up a reusable alert service that can be easily called from anywhere in my application with just: alertService.showAlert('warning', 'something went wrong!'); One example of where I want to use this is after an AJAX ca ...

What is causing my animation to jump when using the Web Animation API reverse() function?

I've come across various sources stating that when you call reverse() while an animation is playing, it should have the same effect as setting playbackRate to -1. However, in my case, using reverse() makes my animation behave erratically and jump arou ...

Setting header details for optimal data transfer

Currently, there is a Java code snippet that I am working on which attempts to access the header information sent by an HTML page. Unfortunately, I do not currently have the specific HTML page in question. However, I still need to be able to access and m ...

Identifying the presence of node.js on your system

After installing node.js, I found myself at a loss on how to run applications. Despite the lack of instructions, I was determined to test if it was working by executing a script named hello.js: console.log('hello world'); I couldn't help b ...

Is it possible to close the menu by clicking outside a div or letting it disappear on mouseout after a set period of time?

When visiting a website, you may notice menus that display sub-menus when hovered over. These menus and sub-menus are created using div elements, with the sub-menus hidden initially using style.display = none; The issue arises when a sub-menu is opened an ...

Encountering a ReferenceError while debugging MongoDB: The console object is undefined

Using a js file within mongodb, I implemented a code snippet containing a console.log expression for debugging purposes: use test; db.city.find().snapshot().forEach(function(city){ var Pos = city.Pos; if (Pos) { longLat = Pos.split(" ...

The JavaScript Ajax request appears to be malfunctioning in both Firefox and Google Chrome, however, it seems to be functioning properly

I am currently using JavaScript to make an Ajax request to communicate with an Arduino webserver and dynamically update the content on a webpage. While this functionality has been working smoothly in Safari, I have encountered issues when trying to use it ...