Continuous loop of Vue countdown timer

Hey there! I'm currently working on implementing a countdown timer, but I keep encountering a console error that says 'You may have an infinite update loop in a component render function.' It seems like something needs to be adjusted.

export default {
  data: () => ({
    timeDiff: 0,
    time: {
      days: 0,
      hours: 0,
      minutes: 0,
      seconds: 0,
    },
  }),
  created(){
    this.startCountdown();
  },
  methods: {
    startCountdown() {
      setTimeout(() => {
        if (this.$store.state.allDataLoaded) {
          var countDownDate = new Date('December 17, 2019 03:24:00');
          var now = new Date();
          this.timeDiff = countDownDate - now;
          this.time.days = Math.floor(this.timeDiff / (1000 * 60 * 60 * 24));
          this.time.hours = Math.floor((this.timeDiff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
          this.time.minutes = Math.floor((this.timeDiff % (1000 * 60 * 60)) / (1000 * 60));
          this.time.seconds = Math.floor((this.timeDiff % (1000 * 60)) / 1000);
        } else {
          this.timeDiff = -1;
          this.time.days = 0;
          this.time.hours = 0;
          this.time.minutes = 0;
          this.time.seconds = 0;
        }
        this.startCountdown()
      }, 1000)
    },
  },
  computed: {
    timeDifferenceComp(){
      return this.timeDiff
    },
    timeComponents(){
      return this.time
    },
  }
};

Answer №1

var timerApp = new Vue({
  template: '<div>{{ remaining.days }} days, {{ remaining.hours }} hours, {{ remaining.minutes }} mins, {{ remaining.seconds }} sec</div>',
  data:
    {
      counter: 0,
      countdown: new Date('2022-01-05T12:30:00Z')
    },
    created: function()
    {
      this.startTimer();
    },
    methods:
    {
      startTimer: function()
      {
        setTimeout(this.updateTimer, 1000);
      },
      updateTimer: function()
      {
        this.counter++;
        this.startTimer();
      }
    },
    computed:
    {
      remaining: function()
      {
        var tmp = this.counter + 1; // invalidate cached value to trigger re-rendering
        var timeDiff = this.countdown.getTime() - Date.now();
        return {
          days: Math.floor(timeDiff / (1000 * 60 * 60 * 24)),
          hours: Math.floor((timeDiff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)),
          minutes: Math.floor((timeDiff % (1000 * 60 * 60)) / (1000 * 60)),
          seconds: Math.floor((timeDiff % (1000 * 60)) / 1000),
        }
      }  
    },
    }).$mount('#timer');
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="timer"></div>

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

"The issue with ExpressJS deleteRoute is that it is not properly refreshing user

I have a specific issue with my express controller for deleting user posts. The problem is that while the post is being removed from the page successfully, it is not getting deleted from the User.posts data as expected. function deleteRoute(req, res) { ...

Is there a way to incorporate an animated element within the track of my circular progress bar?

My circular progress bar features two paths, with one path increasing in length as data is received, eventually turning the entire circle red. Here is the SVG HTML code: <path d="M 50,50 m 0,-47 a 47,47 0 1 1 0,94 a 47,47 0 1 1 0,-94" stroke="#A9B0B7" ...

Tips for adjusting the height of MUI Date Picker to fit your preferences

<Box sx={{ m: 1 }}> <LocalizationProvider dateAdapter={AdapterDayjs}> <DatePicker label="Enter Date" slotProps={{ textField: { height: "10px" } }} ...

Make sure the division remains fixed even when the window is resized

Having a fixed position and bottom set to 0, I want my div to display at the bottom of the window. The issue arises when the window is resized, causing the div to move up and into other elements. For instance, when opening the console box in Chrome, the f ...

When using mapStateToProps in React Redux, it may encounter difficulties in reading nested values

I feel like I must be overlooking something very obvious, possibly related to Immutable.js/React/Redux. Here is a method I have... function mapStateToProps(state){ console.log(JSON.stringify(state.test)); //prints all nested properties and object ...

Having difficulties sending data from axios to my node server, resulting in an empty object being returned

Here is the client-side code I am using: <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport&quo ...

Access Mixins Throughout Your Entire Vue 3 Application

I'm a beginner with vue and I'm currently exploring the use of Websockets for my project. I want to make my websocket-plugin accessible from every component in my app, so I thought about using 'provide' and 'inject'? In my ma ...

Issues with the play() method in Javascript across Firefox, Safari, and IE 11 are causing functionality problems

I developed a basic video and audio player that smoothly fades out an introductory image and starts or stops playing an mp4 file upon click. Everything functions properly in Chrome, but unfortunately does not work in other major browsers. Despite checking ...

Issue with JSON encoded data in "kg-bot/laravel-localization-to-vue" package

After implementing the Laravel localization to Vue extension from https://github.com/kg-bot/laravel-localization-to-vue and extensive debugging, I finally discovered the error preventing it from working as intended. The extension utilizes lang.js, which st ...

Tips for presenting HTML source code with appropriate tag coloring, style, and indentation similar to that found in editors

I need to display the source code of an HTML file that is rendered in an iframe. The source code should be shown with proper tag colors and indentations similar to editors like Sublime Text. https://i.stack.imgur.com/IbHr0.png I managed to extract the sour ...

What is the process for 'injecting' data into a Vue component?

Trying to understand components better and struggling to adapt the official vuejs.org guide examples from new Vue({...}) to the module structure in a newly created Vue app using the CLI. If I have something like this: const products = { 'bat': ...

Having trouble deploying my Express/Next app on Netlify

I am facing issues deploying my Next/Express app on Netlify. While the app functions perfectly locally, I encounter problems when attempting to deploy it using Netlify lambda function. Here are the links to my test git repositories: https://github.com/La ...

Warning: Attempting to modify a property that is not defined - 'action'

My code includes a datatable and an alert that pops out. The datatable functions properly with or without the alert, but the alert does not work well when combined with the datatable. Could this be causing a conflict in the code? An error message indicates ...

Vue 3: Customizing the Appearance of a Specific Slot

After researching extensively on stackoverflow and Vue 3 documentation, I am still unable to find a solution to my specific problem. I am attempting to target a named slot, access the scoped element within that slot, and modify the styles of one of its ch ...

Issues with executing google.script.run in Google Web App

I am encountering an issue with the function I have defined in my .gs file: function doGet(e) { return HtmlService.createHtmlOutputFromFile('index') } function goToMaster() { const ss = SpreadsheetApp.getActiveSpreadsheet() const sheet = s ...

Object Literal vs Object-Oriented Javascript: Comparing the Two

When it comes to using Object-Oriented Programming (OOP) in JavaScript, I often find myself not utilizing it much. For instance, instead of defining a constructor function and setting up prototypes like this: function Person(name){ return this.name = name ...

What is the best way to create an impact?

Need help fixing the parallax effect on this page. I attempted to implement a parallax effect but encountered some issues. Here is the JavaScript code: $objWindow = $(window); $('section[data-type="background"]').each(function(){ var $bgOb ...

Adjusting the size of icons to fit within a container

I need a div that can display up to 7 icons, depending on certain selections. These icons are from ionicons library. Here is the current code snippet: <div class="item item-text-wrap" style="text-align:center;"> <button class="button" style=" ...

React useEffect appended script not activating

I'm having trouble loading a script that should generate an iframe and display a weather widget upon trigger. I am able to append the script correctly, but it doesn't seem to be called and does not create the iframe. Even when I directly add the ...

Incorporating 'image-rendering: -webkit-optimize-contrast' into your tailwind.config.js: A Step-by-Step Guide

I'm looking for a more efficient way to utilize image-rendering: -webkit-optimize-contrast across different components within my Vue application without having to declare it in each component using <style scoped>. The only information I could f ...