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");
}