停止 setTimeout 延迟首次运行
因此,我正在创建一个脚本,在我的网站页面上添加漂浮的云。然而,如此示例所示,第一朵云的出现因 setTimeout 延迟(10-12 秒)
在 spawn_cloud_loop
中。有什么办法可以强制立即添加第一个云而不会造成延迟。我尝试在 spawn_cloud_loop();
之前添加 add_cloud();
但延迟仍然存在。整个项目可以在 https://github.com/JordanAdams/jordanadams.github 找到。 com 以及 js/clouds.js
中的云效果代码。
约旦
So I'm creating a script which adds clouds floating across the page on my website. However as seen in this example, the first cloud's appearance is delayed (10-12 seconds) by the setTimeout
in spawn_cloud_loop
. Is there any way to force the first cloud to be added instantly without the delay. I have tried adding add_cloud();
before spawn_cloud_loop();
but the delay is still there. The project as a whole can be found at https://github.com/JordanAdams/jordanadams.github.com and the code for the cloud effect in js/clouds.js
.
Jordan
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的
clouds.js
脚本包含在头部,然后add_cloud();
立即运行。这意味着您创建一个新的云并尝试将其附加到不存在的“云”div,因为它尚未被解析。第二个和后续的云创建正常,因为spawn_cloud_loop()
函数有很长的延迟,以至于文档已被 then 解析。您需要将clouds.js脚本包含移动到页面源中“clouds”div下方的某个位置,或者将
add_cloud();
调用放入文档就绪处理程序中,以便它不会被执行直到解析“clouds”div 后:注意:如果您修改了
spawn_cloud_loop()
来调用,则不需要初始调用add_cloud()
在设置超时之前add_cloud()
:(当然,您仍然需要从准备好的文档中调用
spawn_cloud_loop()
。)此外,您不需要 <如果您在动画结束时立即从 删除每个云,则根本不会执行 code>clean_up() 过程jQuery
.animate()
方法的完整回调:Your
clouds.js
script is included in the head and thenadd_cloud();
is run immediately. Which means you create a new cloud and try to append it to the "clouds" div which doesn't exist because it hasn't been parsed yet. The second and subsequent clouds are created OK because thespawn_cloud_loop()
function has such a long delay that the document has been parsed by the then.You need to either move the clouds.js script inclusion down somewhere below the "clouds" div in your page source or put the
add_cloud();
call in a document ready handler so that it isn't executed until after the "clouds" div has been parsed:Note: you wouldn't need the initial call to
add_cloud()
if you modified yourspawn_cloud_loop()
to calladd_cloud()
before setting the timeout:(Of course you'd still need to call
spawn_cloud_loop()
from a document ready.)Also, you wouldn't need a
clean_up()
process at all if you delete each cloud immediately at the end of the animation from the jQuery.animate()
method's complete callback: