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

Challenges with 'this' reference in a requireif causing Vuelidate complications

     Need help with vuejs component using vuelidate and validations:     validations: {      invoice: {          dueDate: {              required,          },          tax: {              require ...

What is the process for importing an md file in a create-react-app project using JavaScript?

Attempting to execute the blog example provided on Material UI's getting started page. However, encountering an issue with the source code: Inside blog.js import post1 from './blog-post.1.md'; . . . return( <Main>{post1}<Main/> ...

How can you assign a default value in a React select dropdown and dynamically add the remaining values?

I'm currently developing a React application that includes a form with a select dropdown feature. My goal is to have the 'uom' field value from the selected product record automatically set as the default option in the dropdown when the user ...

Using curly braces when invoking a function from HTML within a Vue.js application

When I call a function, for example on click, it works whether or not I use curly braces. However, I have created a function that triggers a custom event from a child component. I then await this event in a parent component and update the state with my par ...

Leveraging Window Object in Custom Hooks with NextJS

ReferenceError: window is not defined This issue arises on the server side when NextJS attempts to render the page. However, it is possible to utilize window within the useEffect hook by following the guidance provided here. I am seeking advice on creati ...

Is there a way to create tabs in JavaScript without having to edit the <head> section?

I am in need of JavaScript for creating tabs without the necessity of editing the <head> (as it is not possible). My requirement involves having three links and three divs. Whenever a link is clicked, one specific div should be displayed while the o ...

"PHP, AJAX, and JavaScript work together to run a loop that processes only the final element

Hello everyone, I need assistance in saving data from a loop. Here is the code snippet that I am working with: <html> <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> </head> ...

Discord.js Lock Command Implementation

I've developed a lock command for discord.js, but every time I try to run the command, I encounter an error. Here's the code snippet: module.exports = { name: "lock", description: "Lock", async run(client, message ...

I have developed a custom jQuery carousel that includes functionality to start and stop the carousel based on specific conditions

I have set up a jQuery carousel that moves to the left when a checkbox is checked, but I need it to stop moving when the checkbox is unchecked. Can someone help me achieve this? $("#checkBox").click(function(){ if($(this).prop("checked") == true){ ...

Improving conditional rendering in Mui <Cards> component by fixing state behavior

I have a situation where I want to display a Floating Action Button inside each Mui card when hovered over. However, I'm running into an issue with the hover state affecting all cards instead of just the one being interacted with. How can I ensure tha ...

Listener for 'timeupdate' event on video doesn't retain values

My html5 video event listener is designed to pause the video at a specific time while the user participates in a quiz. The first 'lesson' works fine, and the second video also appears to add the listener with the correct pause time. However, when ...

The window.open function is creating a new tab using the specified origin or URL

I have a button within an iframe on the webpage "loclahost:3000". When this button is clicked, it should open a new tab with the URL "www.google.com". However, instead of opening the desired URL, the new tab opens with the following incorrect URL: "http:// ...

Retrieve information from both the client and server sides within NextJS

Looking to integrate a third-party API for data fetching in certain components within my NextJS project. The goal is to have the server pre-render these components with the API for optimal SEO benefits, but also enable client-side fetching of component pro ...

ng-required is ineffective when used with number inputs that have a minimum value requirement

In my form, I have implemented a checkbox that, when checked, toggles the visibility of a div using AngularJS's ng-show. Within this div, there is an input field of type "number" with a validation setting of min="10000". I am trying to prevent the f ...

Concealing items in a loop using Javascript

I need assistance with this issue. I am trying to hide text by clicking on a link, but it doesn't seem to be working correctly. Even though I tried the following code, I can't figure out why it's not functioning as expected. Is there a diff ...

A Vue element that has multiple exact click handlers will consistently trigger the click.exact method when clicked with system modifiers

According to the information found at https://v2.vuejs.org/v2/guide/events.html#exact-Modifier, I am attempting to build an element that triggers different methods based on additional keys pressed at the time of clicking. <span @click.exact="method ...

The setInterval() function within a jQuery dialog continues running even after being destroyed or removed

I'm facing an issue with a jQuery dialog that loads an external page and runs a setInterval() function querying the server continuously every second via AJAX. The problem arises when I close the dialog, as the setInterval keeps running. Below is the ...

Tips on converting Django model into desired format for Bootstrap-tables plugin integration

I want to integrate the bootstrap-table plugin with server-side functionality using Django Rest Framework to populate the data on the table. However, I keep getting the message "No matching records found". After some investigation, I discovered that a spec ...

Is there a way to dynamically set the value of a React Material TextField in Auto Select mode?

Here is a React state: const [filterByInvoiceNo, setFilterByInvoiceNo] = useState( 0 ); This represents a React Material TextField: <TextField size="small" type="number" label="Invoice No&quo ...

Easily move elements using a jQuery click animation

Having trouble animating a div's top position by -130px to move it off screen? Can't figure out why it's not working? I'm fairly new to jQuery/Javascript. I have a button/hyperlink with the ID #NavShrink. When clicked, I want the div # ...