request time in AJAX

4

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

I'm doing 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 this?

    
asked by anonymous 08.03.2017 / 15:28

1 answer

4

You can use a combo with variable status and 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);
    }
  });
});
  • You create a loader status variable, leaving it initially as false .
  • Before the AJAX call, a timeout of 2 seconds is created and if the time expires and the AJAX call is not finished, loader will appear.
  • When the call terminates, it will check the loader status with the showLoader variable, if it is true , hide the loader , otherwise clean timeout , so it does not run and show loader .
  • There are other ways to do it, but this is one of them. One note: 2 seconds is a short time, see if there is really a need for this in your AJAX call, see if it takes too long or is too fast.

        
    08.03.2017 / 16:01