Here we have an example of a dummy project: An app with a counter feature that allows for both increment and decrement functions which change two different values ("life" and "count") and also keeps a record of the changes.
The "life" value behaves as expected when using either of the functions. However, the "count" value has a peculiar behavior: it always increases by 2 regardless of which function is used.
For a live demonstration, you can check out this link: https://codepen.io/Olivier_Tvx/pen/JjdyBMO?editors=1111
Can you spot what might be going wrong with this implementation?
JavaScript Code:
let player = {
data: function () {
return {
life: '20',
poison: '0',
timer: '1500',
count: '0',
historics: [{
value: '',
}],
}
},
methods: {
increaseLife: function() {
clearTimeout(this.timer);
clearTimeout(this.count);
this.life++;
this.count++;
this.timer = setTimeout(() => { this.pushToHistorics() }, 1500);
this.count = setTimeout(() => { this.countClear() }, 1000)
},
decreaseLife: function() {
clearTimeout(this.timer);
clearTimeout(this.count);
this.count--;
this.life--;
this.timer = setTimeout(() => {this.pushToHistorics() }, 1500);
this.count = setTimeout(() => { this.countClear() }, 1000)
},
countClear: function() {
this.count = 0;
},
reset: function() {
this.life = 20;
this.poison = 0;
this.historics = [];
this.count = 0;
},
pushToHistorics: function() {
this.historics.push({
value: this.life,
})
},
},
template: `
<div class="global">
<div class="count"><span v-show="count > 0">counter : {{ count }}</span></div>
<div>PV : {{ life }} </div>
<span>Poison : {{ poison }} </span>
<div class="containterBtn">
<button @click="increaseLife(); increaseCount()">+</button>
<button @click="decreaseLife()">-</button>
<button @click="reset()">reset</button>
</div>
<div class="historics" v-for="historic in historics.slice(0, 10)">
<div class="historic">{{ historic.value }}</div>
</div>
</div>
`
};
let vm = new Vue({
el: '#app',
components: {player},
});