Understanding the Behavior of Vue 3's setInterval Methods

Environment

I am working on a Vue 3 Application where I need to run a constant setInterval() in the background (Game Loop).

To achieve this, I have placed the code in store/index.js and invoked it from views/Playground.vue's mounted() lifecycle hook. When leaving the Playground, I make sure to call beforeUnmount() to prevent multiple instances of setInterval() running simultaneously.

// store/index.js
startGameLoop({ commit, dispatch, getters }) {
  commit(
    "setIntervalId",
    setInterval(() => {
      dispatch("addPower", getters["ship/getFuelPerSecond"]);
    }, 1000)
  );
},

// Playground.vue
beforeUnmount() {
  clearInterval(this.intervalId);
}

In the upper section of Playground.vue, there is a score displayed that gets updated within the setInterval(). I use a library named gsap to add some visual appeal to the changing numbers.

<h2>Points: {{ tweened.toFixed(0) }}</h2>
watch: {
  points(n) {
    console.log("gsap");
    gsap.to(this, { duration: 0.2, tweened: Number(n) || 0 });
  },
},

Issue at Hand

The methods within the Playground.vue seem to be triggering inconsistently, and I am having trouble understanding why.

gsap

The watch function associated with gsap behaves as expected, firing every second similar to the setInterval(), but...

Image

In the center of the Playground, an image is displayed where the src attribute is bound to a method called getEnemyShipImage. Despite my intentions for future programmatic changes to the displayed enemy ship, the method is being called a whopping 34 times per second. This behavior has left me scratching my head.

<img
   :class="{ flashing: flash }"
   @click="fightEnemy()"
   :src="getEnemyShipImage()"
   alt=""
/>

getEnemyShipImage() {
   console.log("image");
   return require("@/assets/ships/ship-001.png");
}

Browser Logs

Link to Console Log Output

Answer №1

relocated it to a section without relying on a technique and updated the process of changing images to a monitoring system.

data: () => {
  return {
    ...
    selectedImages: "",
    images: [
      require("@/assets/ships/ship-001.png"),
      require("@/assets/ships/ship-002.png"),
      require("@/assets/ships/ship-003.png"),
    ],
  };
},

// initial value
mounted() {
  this.selectedImages =
    this.images[Math.floor(Math.random() * this.images.length)];
  this.$store.dispatch("startGameLoop");
}

// watch score
watch: {
    score() {
    this.selectedImages =
      this.images[Math.floor(Math.random() * this.images.length)];
  },
}

it's not flawless but an improvement from the original version.

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

Is there a way to configure multiple entry points in a package.json file?

I am looking to execute various commands using npm: "scripts": { "v1": "node v1.js", "v2": "node v2.js" } I would like to use npm start v1 or npm start v2 for this purpose, however, these commands do not seem to trigger the intended Node command. ...

Are you still relying on outdated endpoint pagination with Vue and Laravel?

Currently, I am in the process of transitioning a Laravel app from using Blade files to implementing Vue. In one part of the app, we had used pagination for displaying users with a page parameter at the end of the endpoint URL. For instance: /store/api ...

Obtaining font resources within a Vue application on a WordPress page template

When it comes to posting a question, I usually refrain from doing so unless I truly cannot find an answer. Unfortunately, that seems to be the case now. I am currently managing a project where a Vue app is being deployed within a page of a WordPress site. ...

Extracting the JQuery library from its source code

Is there a simple method for extracting only the necessary functions from the jQuery library? I have found that many of the functions within the library are not being utilized, so it would be beneficial to remove them. ...

Creating a collection of interconnected strings with various combinations and mixed orders

I am currently working on creating a cognitive experiment for a professor using jsPsych. The experiment involves around 200 logical statements in the format T ∧ F ∨ T with 4 different spacing variations. My main challenge is to figure out a way to a ...

ProgressMeterJS Plugin - Full-width Progress Bar

I have encountered a question regarding this particular plugin found at: My goal is to adjust the progress bar's width to 100% so it matches the width of its container. So far, I have made modifications to the plugin by changing the following line: ...

Issues arise in Angular 4 when the "Subscribe" function is repeatedly invoked within a for/switch loop

My array of strings always changes, for example: ["consumables", "spells", "spells", "consumables", "spells", "consumables", "spells", "characters", "characters", "consumables"] I iterate through this array and based on the index, I execute different .su ...

The altered variable refuses to show up

Currently, I am working on a project to create a Skate Dice program that will select random numbers and display the results simultaneously. Unfortunately, I have encountered an issue where the randomly generated number is not being shown; instead, it dis ...

Using Unicode JSON in Laravel blade to pass data to React components, encountering an issue with JSON parsing

I currently have a JSON object stored in the database: { "ui": {}, "title": "Hola mundo 2", "values": {}, "properties": {}, "description": "descripcion" } Within the Laravel controller, ...

The dimensions of the body are set to 100vh in height and width. However, the div inside this body has a width of either 100vh or 100%, but it is not

I am trying to create a div element that has a width equal to the viewport of the browser. However, I am encountering issues when applying the CSS property width:100vh to the body element. Here is my code snippet: body { font-family: Staatliches; fo ...

Exploring Angular 4: Embracing the Power of Observables

I am currently working on a project that involves loading and selecting clients (not users, but more like customers). However, I have encountered an issue where I am unable to subscribe to the Observables being loaded in my component. Despite trying vario ...

Within Vuex, the object store.state.activities contains a specific key labeled "list" which initially holds an array of three items. However, when attempting to access store.state.activities.list directly, an empty array

My project is utilizing Vue. The store.state.activities object contains 2 keys, including an array named list with 3 elements. However, despite attempting to access it using store.state.activities.list, I am getting an empty array. I have experimented w ...

Unable to integrate third-party tools into your Vue JS project via CDN

Currently delving into Vue JS to enhance the interactivity of my django application, I am opting for the route of integrating Vue JS as components within my templates rather than going down the path of a Single Page Application (SPA). It's almost like ...

What steps are necessary to create an npm package utilizing three.js without any dependencies?

I have a challenge - I am trying to create an npm package that generates procedural objects for three.js. The issue I'm facing is how to properly include three.js in my code. I attempted to establish a dependency and use something like const THREE = r ...

Obtaining zip files using AngularJS

Upon entering the following URL in my browser, I am prompted to download a file: My goal is to download this file using an AngularJS HTTP request. I have created a factory for this purpose, but unfortunately, the download is not successful. Even though ...

What are the steps for integrating connect-multiparty into route paths?

I am looking to incorporate connect-multiparty into my routes. Upon researching, I found the following example... var multipart = require('connect-multiparty'); var multipartMiddleware = multipart(); app.post('/upload', multipartMiddle ...

Dynamic JavaScript Animation

Check out this code snippet I currently have. Notice how the text seems to jump when rerun? Give it a try and see for yourself. The big question is: How can this be fixed? $("#aboutUsText").delay(1000).fadeOut(1000) $("#aboutUsText").attr("MyState", "1") ...

What is the response of Express when it encounters numerous identical asynchronous requests from the same origin?

Currently, I am utilizing Express.js for my project. There is an async function that performs a task that can take anywhere from 20 to 30 seconds to complete. Once the task is done, it increases a user's counter in the database. However, users are req ...

Transmitting the character symbol '&' within a string from Angular to PHP

My goal is to transmit a string, such as "the cat & the dog", from Angular to PHP using GET method. I have used encodeURI(note) in Angular and in PHP $note = $_GET['note']; $note = mysql_real_escape_string($note); However, when it gets inse ...

Adding a scrollable feature to a Bootstrap Modal seems to be generating additional unnecessary pages at the

I need help with my scrollable bootstrap modal that has a print button on top. When the user clicks the button, I want to print the modal content. Here is the code snippet: HTML : <div class="container-fluid" id="body-noPrint"> /* HTML BODY CON ...