AJAX request time

Asked

Viewed 1,091 times

4

Well I make a request via AJAX, so I can put a load on the screen and remove it when AJAX loads the page.

The problem is that I need to make the load appear only if the request takes more than 2 seconds.

I’m doing like this:

$(document).ready(function () {
            $(".loading").show();
            $.ajax({
                url: 'APP?pagina=<?= $pagina ?>',
                success: function (response) {
                    $("#app").html(response);
                    $(".loading").hide();
                }
            });
        });

loading is the DIV that counts the loading, and it can only appear if the request takes more than 2 seconds.

Does anyone know how to do that?

  • you know the timeout?

  • Yes I tried to use it here but it was going wrong, because the div was appearing after 2 Monday and did not leave the screen more. I guess I wasn’t doing it right

1 answer

4


You can use a combo with variable status and the setTimeout.

var showLoader = false;

$(document).ready(function () {
  var timeoutLoader = setTimeout(function () {
    showLoader = true;
    $(".loading").show();
  }, 2000); // 2000ms = 2 segundos

  $.ajax({
    url: 'APP?pagina=<?= $pagina ?>',
    success: function (response) {
      if (showLoader) {
        showLoader = false;
      } else {
        clearTimeout(timeoutLoader);
      }

      $(".loading").hide();
      $("#app").html(response);
    }
  });
});
  1. You create a status variable for Loader, leaving her initially as false.
  2. Before the AJAX call, a timeout 2 seconds and in case the time ends and the AJAX call is not finished, the Loader will appear.
  3. When the call ends, it will check the status of the Loader through the variable showLoader, if it’s true, hides the Loader, if not, clean up the timeout, so that he does not execute and show the Loader.

There are other ways to do it, but this is one of them. A remark: 2 seconds is a short time, see if there really is a need for this in your AJAX call, see if it takes too long or is too fast.

  • Thanks worked out, in a matter of 2 seconds I thought so. The site on average takes less than 2 seconds to load, but in reports it can take up to 10 seconds, so I want the loading to appear only when the page takes a while. Got it?

  • There is a problem in your answer, the load does not disappear from the page.

  • Maybe it was a conflict clearTimeout by hiding the Loader. I edited the question and I’m hiding the Loader even if he doesn’t show up.

  • OK vlw friend worked out

Browser other questions tagged

You are not signed in. Login or sign up in order to post.