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>

1

1 Answer 1

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.

3
  • 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 6, 2019 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 7, 2019 at 1:48
  • 3
    Thanks mate, I ended up putting the clearInterval() in the beforeDestory block
    – Moein
    Jun 7, 2019 at 2:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.