8

I need to call the method getBitcoins() every second.

Tried: I tried just taking it out the methods and putting it under the line import Pickaxe from '../assets/pickaxe.png' and then using setInterval to call it every second, but then I can't access the data variable btcPrice inside getBitcoins().

So I need a way to call the getBitcoins() from the methods functions every second, just as it is in the code below.

<template>
  <div id="wrapper">
    <div class="top"></div>
    <!-- Center -->
    <div class="center">
      <img :src="Pickaxe" class="Pickaxe">
      <span class="my-btc">{{ mybtc.toFixed(8) }}</span>
      <span id="btc">1 BTC = {{ btcPrice }}</span>
      <button class="Mine">Mine</button>
      <span class="hashes">{{btcMin}} btc/min</span>
      <button class="Upgrade">UPGRADE</button>
      <span class="upgradePrice">{{ upgradePrice }}btc</span>
    </div>
  </div>
</template>

<script>
  import bitcoin from '../assets/bitcoin.svg'
  import Pickaxe from '../assets/pickaxe.png'

  export default {
    name: 'landing-page',
    data() {
      return {
        bitcoin,
        Pickaxe,
   
        mybtc: 1,
        btcPrice: null,
        btcMin: 0,

        upgradePrice: 0

      }
    },
    methods: {
      getBitcoins() {
        var currentPrice = new XMLHttpRequest();
        currentPrice.open('GET', 'https://api.gdax.com/products/BTC-USD/book', true);
        currentPrice.onreadystatechange = function(){
          if(currentPrice.readyState == 4){
            let ticker = JSON.parse(currentPrice.responseText);
            let price = ticker.bids[0][0];
        document.getElementById('btc').innerHTML = "1 BTC = " + price + "$";
       };
      };
        currentPrice.send();
      }
    }
  }
</script>
Vaffle
  • 107
  • 1
  • 1
  • 7
  • 2
    Possible duplicate of [how to use setInterval in vue component](https://stackoverflow.com/questions/43335477/how-to-use-setinterval-in-vue-component) – t.niese Aug 26 '18 at 11:56

1 Answers1

28

I think this should work for your needs.

created() {
    this.interval = setInterval(() => this.getBitcoins(), 1000);
},

It's not necessary to register this on the created event, you can register it on other method, or even on a watcher. If you do it that way, you'll have to check somehow that it hasn't been registered, cause it may cause multiple loops to run simultaneously.

Erubiel
  • 2,934
  • 14
  • 32
  • I tried this and I face a problem, that is when I go back (to the previous page/component) the function keeps running in the back. How to avoid that? – Moein Jun 06 '19 at 23:28
  • @MoeenMH, save it on a method, call it with the method's name, set another method that calls clearInterval function to stop it. I mean that's the logic, the specific implementation is up to you. – Erubiel Jun 07 '19 at 01:48
  • 3
    Thanks mate, I ended up putting the `clearInterval()` in the `beforeDestory` block – Moein Jun 07 '19 at 02:03