Vue.js setTimeout functionality

Below you can see that the timer is supposed to update the msg after 90 seconds have passed, but instead it updates almost instantly. I am familiar with setInterval and watch, so I'm puzzled as to why the code isn't functioning correctly.

All we are doing here is checking if the counter is above 0, and if it is, spawning another timeout to trigger the current function again, creating a loop of sorts.

var view = new Vue({
  el: '#app',
  data: {
    countDown: 90,
    msg: "There's still time.."
  },
  methods: {
    timer: function () {
      if (this.countDown > 0) {
        setTimeout(() => {
          this.countDown--
          this.timer()
        }, 1000);
      }
      else if(this.countDown === 0);
      {
        this.msg = 'You Ran Outta Time!'
      }
    }
  },
  
  created () {
    this.timer();
  },
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Vue test</title>
</head>
<body>
  <div id="app">
    <h2>{{msg}}</h2>
  </div> 
</body>
</html>

Answer №1

Make sure to delete the ; following else if(this.countDown === 0) as it is considered a statement. Your code should look like this:

if (this.countDown > 0) {
            setTimeout(() => {
              this.countDown--
              console.log(this.countDown)
              this.timer()
            }, 1000);
          }
          else if(this.countDown === 0)
          {
                      
          }
   this.msg = 'You Ran Outta Time!'

var v = new Vue({
  el: '#app',
  data: {
    countDown: 90,
    msg: "There's still time.."
  },
  methods: {
    timer: function () {
      if (this.countDown > 0) {
        setTimeout(() => {
          this.countDown--
          console.log(this.countDown)
          this.timer()
        }, 1000);
      }
      else if(this.countDown === 0)
      {
      
        this.msg = 'You Ran Outta Time!'
      }
    }
  },
  
  created () {
    this.timer();
  },
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Vue test</title>
</head>
<body>
  <div id="app">
    <h2>{{msg}}</h2>
  </div> 
</body>
</html>

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

Using Chart.js to display JSON data in a graphical format

I am facing an issue and need some help. I have gone through various tutorials and questions, but none of them seem to address my specific problem. When making an ajax request to my PHP file, I receive a JSON response like this (as seen in the console log) ...

Using the "i" parameter in a Lodash for loop results in undefined, however, it functions properly with specific values set

My goal is to use Lodash to search for specific integer values in an object and then store some of those values in an array. The integers are variable and come from a separate array, but I am consistently getting undefined as the result. If I manually inp ...

How can I isolate the CSS of my Vue application from the rest of the website?

I am currently working on developing a unique "plugin" that will feature a user interface to be integrated into various vendor websites. This particular plugin is designed to be CMS agnostic, and due to SEO concerns, I am unable to utilize an iframe. My go ...

Using HTML and JavaScript, we can set two different color values - one for the background and one for the h1 title

I am trying to save two values, one for the h1 tag and one for the body background. I want the user to select color 1 and color 2. When I press the third button, all changes should be applied and the colors should change. I have attempted this but with no ...

Testing the Router.push function using Jest and ReactHere is a guide on how

As a beginner in unit testing, I find it challenging to grasp how I can effectively test or mock a push from a router. <Tab label="Members" alt="Members" onClick={() => Router.push('/members')}/> I am particularly concerned about testi ...

Is it possible to use multiple datepicker modals within vuetify?

Here is an example of my Vue component structure: <template> <v-row> <v-col cols="12" sm="6" md="4"> <v-dialog v-for="(item, i) in test" :key="i" ref="dialog" v-model="modal" :return-value.s ...

Changing querySelector() result to a booleandataType

How can I extract the content of an HTML meta tag in Typescript within a React component? <meta name="accepted-cookies" content="false" /> I have attempted to retrieve the value as a boolean using this code: const metaValue = (do ...

Combining the MergeMap and Map operators in RxJS using Typescript

Struggling to grasp the concept of RxJS, I am currently learning and trying to understand this code snippet: mapOfPeople = new Map<number, any>(); const people = [ { name: 'Sue', age: 25 }, { name: 'Joe', age: 30 }, { name: ...

Trouble retrieving data from multiple added rows in Django dynamic fields template

I am currently developing a template that dynamically generates multiple rows of content. After submitting the form, only the last generated row is being saved and I'm not able to retrieve data from all the rows created by the template. I suspect th ...

Experiencing issues with references while trying to import tone.js

I am facing an issue with my express.js server setup on my Mac. I am trying to incorporate Tone.js, which can be found at , following the provided instructions. npm install tone To integrate Tone.js successfully: import * as Tone from 'tone' Ho ...

What is the process for activating the appropriate image when clicking on the accordion?

I currently have three accordions on the left side and three images on the right side, but this may grow in the future. My goal is to have the first accordion open and display the first image when the page loads. When the user clicks on the second accordio ...

Implementing JavaScript templates to display images: A step-by-step guide

I am facing an issue with displaying images on my page. The data for name and address is showing up, but the image is not being displayed. Here is the snippet of my code: var JSONObject = [{ name: 'Nyonya', ...

How can I make the footer on my webpage have a white background?

My goal is to create a white div that spans from point (A) to point (B) on the page, just like in the image. I aim for it to stretch all the way down to cover the entire browser without showing any gray background underneath, even when the page is scrolled ...

Using Node.js to run numerous SQL queries

As a newcomer to node.js, I am working on a demo app using nodeJs. I am encountering an issue when running multiple queries in my code: exports.dashboard = function(req, res){ req.getConnection(function(err,connection){ var id = req.session.userId; ...

Using jQuery to alter an href link's attribute

I am currently attempting to modify the content of a href using jQuery. After researching various solutions on this platform, I came across one that I am trying to use for implementation: How to change the href for a hyperlink using jQuery My current app ...

What is the best way to display items from top to bottom in React?

Currently, I am working with a list of objects structured in this way: const items = [{name: 'some name', count: 'how many of that name'}, ...] My goal is to display them in the following format: {items.map((item) => ( ...

Retrieving a component from a webpage with Cypress

https://i.sstatic.net/ZvlGU.png I am trying to extract just the order ID from the href attribute using Cypress. Can anyone assist me with this? Below is my Cypress code snippet: `cy.get('[href="/practice/orders"]').click() cy.get(& ...

Display the DIV element once a specific number of radio buttons have been selected

I need help figuring out how to display a DIV after a specific number of radio buttons are selected. Currently, I have it set up to appear only when all the radio buttons are selected thanks to some guidance from others who had similar questions. However, ...

Is it possible for this solution to be compatible with IE7 and IE6?

Is there a way to enhance this solution for compatibility with IE6 and IE7? http://jsfiddle.net/kirkstrobeck/sDh7s/1/ Referenced from this discussion After some research, I have come up with a practical solution. I've converted it into a new func ...

Locating a unique element within a JavaScript array

After creating a JavaScript class as shown below: function chat(data){ this.id = data.id; this.name = data.name; this.message = data.message this.date = data.date; } I then initialize an empty array like so: var message = []; and ...