How can I call a method every x seconds?

Viewed 17231

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>

1 Answers

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.

Related