简体   繁体   English

如何在函数执行前进行正确的延迟?

[英]How to make a correct delay before function executing?

So, I'm trying to do a loading animation for my website on ASP.NET WebForms. 因此,我正在尝试为ASP.NET WebForms上的网站制作加载动画。 I have noticed that some pages are loading really fast and some are not. 我注意到有些页面的加载速度非常快,而有些却不是。 I have made an execution of an animation in this way: 我以这种方式执行了动画:

$(document).ready(function () {

         $('#loadingImage').hide();
         $('#loading').html("");
     });

But now I want to make a delay, approximately in 1-2 sec for pages that load fast to not show the animation for them. 但是,现在我想延迟一下,对于快速加载的页面大约要在1-2秒内不显示动画。 I try to do this in this way: 我尝试通过这种方式做到这一点:

setTimeout(checkDocument, 3000);

  function hideLoading() {
      $('#loadingImage').hide();
      $('#loading').html("");
  }

  function checkDocument() {
      $(document).ready(hideLoading);
  };

My HTML code: 我的HTML代码:

 <div id="loading" style="text-align: center" ><asp:Image ID="loadingImage" runat="server"  ImageUrl="~/Images/loading.gif" /></div>

So, this works wrong. 因此,这是错误的。 This code executed my animation at once and then off the animation in 3 seconds. 这段代码立即执行了我的动画,然后在3秒内关闭了动画。 Help to find out the right way for this. 帮助找出正确的方法。 And one more, I have this line of code 另外,我有这一行代码

$('#loading').html("");

Why if we not use nothing as argument in html part, then animation can't stop, when we take "" to the html then everything works. 为什么如果我们不使用任何内容作为html部分中的参数,动画就无法停止,当我们将“”作为html时,一切都将起作用。 Please, explain this moment. 请解释一下这一刻。

What you need to do is make the loading animation invisible at first, and then make it visible after a delay. 您需要做的是首先使加载的动画不可见,然后在延迟后使其可见。 Finally, use the document.ready event to hide it when everything is loaded. 最后,在所有内容加载完毕后,使用document.ready事件将其隐藏。 What you're doing right now is just delaying the creation of the document.ready event handler, which makes no sense. 您现在正在做的只是延迟document.ready事件处理程序的创建,这没有任何意义。 (Don't forget, creating an event handler doesn't actually execute the function immediately, it just creates something which listens for the event occurring in the future.) (不要忘记,创建事件处理程序实际上并不会立即执行该函数,它只会创建一些内容来监听将来发生的事件。)

Change your div definition to 将您的div定义更改为

<div id="loading" style="text-align: center" hidden>

It should be the first thing that's put into the <body> section of your page, if possible. 如果可能的话,应该将它放在页面的<body>部分中。

Then, immediately below it, put the following script tag: 然后,在其下方放置以下脚本标记:

<script>
  function showLoading() {
    $("#loading").show();
  }

  var loadingTimeout = setTimeout(showLoading, 3000);

  $(document).ready(function() {
    clearTimeout(loadingTimeout); //make sure loader doesn't appear if page loads in less than 3 seconds
    $("#loading").hide();
  });
</script>

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

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