0

I have some data that is live updated to a Google sheet as an integer that I am inserting into the HTML on my page that then uses Javascript to animate the numbers counting up to the stored figure.

Unfortunately data from Google sheets isn't received before the counter function activates so upon page loading my counter displays 0 but when the page is refreshed everything works counting up to the number stored in sheets.

If the counter function could be delayed until the sheet data has been received I believe this can function as intended.

I am an amateur at html & Javascript so may have incorrectly implemented these but I have attempted:

-placing defer inside < script >

-inserting setTimeout (setTimeout seems most likely to achieve what I need but I can't get it to delay the counter correctly)

-- the counter script in my html --

<script>
jQuery(document).ready(function( $ )
{
    $(".counter").counterUp({
    delay: 10,
    time: 1000,
    });
}) ;
</script>

I expect the page to load and numbers to count up to the figure I have stored in a Google Sheets folder. Currently it displays 0 on page loads and only works correctly after refreshing the page.

Thank you in advance.

THCoding
  • 1
  • 1

1 Answers1

0

The current generation of Javascript in browsers does not have a wait() or sleep() that allows other things to run. So, you simply can't do what you're asking. Instead, it has async operations that will do their thing and then call you when they're done (as you've been using promises for).

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

function waitForDataLoad() {
  return new Promise(function(resolve, reject) {
      // process your data load or any processs
      setTimeout(function(){
       resolve();
      },3000)

    
  })
}

waitForDataLoad().then(function(result) {
    // use the result here
    // Further process here
    // this script will be only loaded when above function return resolve();
    console.log("data is loaded compeletly")
});
Rishab
  • 1,484
  • 2
  • 11
  • 22