Search code examples
javascriptodometer

Odometer.js Keeps Updating From 0


I'm working on a counter that shows the total amount of trees from TeamTrees.org (I'm new to JavaScript) Which I wanted to make it real-time. So, I use Odometer.js and it keeps updating from 0.

Here's the video to describe my problem. removed

I've tried searching on this site, and other Sites. But, it still didn't work.

Here's the code:

index.html

</div>
    <script src="trees.js"></script>
    <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/odometer.js/0.4.8/odometer.min.js"></script>
    <script>
    init();

     var TreeCount = new Odometer({ 
        el: document.querySelector('#cash'),
        auto: 'true', 
        format: ',ddd', 
        theme: 'default'
         }) 
    </script>
    </center>
</body>

Trees.js

function init() { 
fetchTrees() 
setInterval(fetchTrees, 3000);
   } 
  function formatNumber(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    }
 function fetchTrees() { 
   $.ajax({
    url: "-",
    method: "POST",
  data: {
   "wrapAPIKey": "-"
 }
  }).done(function(data) {
    numTrees = data["data"]["#totalTrees"]; 

  $("#cash").text("$"+formatNumber(numTrees))
  TreeCount.update(numTrees); 
   });
 } 

Solution

  • I think that you need to add the last retrieved value to the new value like so :

    function init() { 
    fetchTrees() 
    setInterval(fetchTrees, 3000);
       } 
      function formatNumber(x) {
    return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
        }
     function fetchTrees() { 
       $.ajax({
        url: "-",
        method: "POST",
      data: {
       "wrapAPIKey": "-"
     }
      }).done(function(data) {
        numTrees += parseInt(data["data"]["#totalTrees"]); 
    
      $("#cash").text("$"+formatNumber(numTrees))
      TreeCount.update(numTrees); 
       });
     }