0

I want to perform a while loop with one second of interval.

The method which I want to operate is;

new Vue({
    el: "#app14",
    data: {
        dealerCards: [],
    },
    computed: {
        dealerHand() {
            return CalcHand(this.dealerCards);
        }
    },
    methods: {
        Stand: function() {
            while (this.dealerHand < 17) {
                this.dealerCards.push(Draw());
                console.log("DH: " + this.dealerHand);
            }
        },
    },
});

CalcHand returns the sum of the input array.

I rewrite it with setInterval function;

var dd = setInterval(function() {
    this.dealerCards.push(Draw());
    console.log("DH: " + this.dealerHand);

    if (this.dealerHand >= 17) {
        clearInterval(dd);
        return;
    }
}, 1000);

However, browser console said this.dealerCards is undefined. I wonder if you have any idea why this error shows up.


I rewrote it like this. It works once a second, but not stop.

setInterval(() => {
    this.dealerCards.push(Draw());
    console.log("DH: " + this.dealerHand);

    if (this.dealerHand >= 17) {
        clearInterval();
        return;
    }
}, 1000);
Kota.M
  • 117
  • 7
  • We don't have enough information. Where is `this.dealerCards` initialized? Where is `this.dealerHand` initialized? – Samathingamajig Nov 18 '20 at 16:22
  • I added the entire Vue instance. – Kota.M Nov 18 '20 at 16:34
  • Use an arrow function to bind the context to the Vue instance: `setInterval(() => {...})` – tony19 Nov 18 '20 at 18:16
  • Thank you for helping. It is performed once a second as I expect, but it does not stop. – Kota.M Nov 18 '20 at 18:43
  • It has been fixed and works now, thank you. Somehow the question is closed, so I post it again. System says that this question has already answered, but I do not think so. – Kota.M Nov 18 '20 at 19:00
  • I have re-posted it with my answer here; https://stackoverflow.com/questions/64899697/function-of-setinterval-in-vue-js – Kota.M Nov 18 '20 at 19:05

0 Answers0