简体   繁体   English

延迟Javascript函数,直到加载数据

[英]Delay Javascript function until data loaded

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. 我有一些数据作为整数被实时更新到Google工作表中,然后将其插入页面HTML中,然后使用Javascript来对数字进行动画处理,直到存储的数字为止。

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. 不幸的是,在激活计数器功能之前未收到来自Google工作表的数据,因此,在页面加载时,我的计数器显示为0,但是刷新页面后,所有内容都可以计数到工作表中存储的数量。

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: 我是html和Javascript的业余爱好者,所以可能错误地实现了这些功能,但是我尝试过:

-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) -插入setTimeout(setTimeout似乎最有可能实现我需要的功能,但我无法正确延迟计数器)

-- the counter script in my html -- -我的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. 我希望页面加载,并且数字可以计数到我存储在Google表格文件夹中的数字。 Currently it displays 0 on page loads and only works correctly after refreshing the page. 当前,它在页面加载时显示0,并且仅在刷新页面后才能正常工作。

Thank you in advance. 先感谢您。

The current generation of Javascript in browsers does not have a wait() or sleep() that allows other things to run. 浏览器中当前生成的Javascript没有允许其他事情运行的wait()或sleep()。 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). 相反,它具有异步操作,可以执行其操作,然后在完成操作后调用您(因为您一直在使用promises)。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise https://developer.mozilla.org/zh-CN/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") }); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM