How to delay

Hi,

I am having trouble how do i use the delay before sending a request,what i want is to delay about 3secs to show my loading bar and make a request to server.

i tried this
beforeSend:function() {
<div><img src=“loadingbar.gif”></img></div>.delay(3); //3 seconds.
}

Thank you in advance :slight_smile:

Unfortunately, you cannot call delay() on random HTML :slight_smile:

In this case, just use setTimeout:

function doAjax(){
  // Server request here
}

$("myElement").on("click", function(){
  setTimeout(doAjax, 3000);
});

Hope that helps.

Hi Pullo, Thank you so much it’s working :slight_smile:

I have some question about when do we use beforeSend() ?..i thought this is use by some website that i had seen that will display something like this “please wait…” when we submit some forms to the server…so in my point of view of this did they also used setTimeout ?please correct me if i am wrong.

Thank you :slight_smile:

Hi jemz,

The problem here is the asynchronous nature of JavaScript.

If you do something like:

$.ajax({
  type: "GET",
  url: "test.php",
  beforeSend: function(){
    img.fadeIn(2000);
  },
  success:function(res)  {
    $("#result").html(res);
  }
});

The jQuery will call the beforeSend function, before making the GET request, but it will not wait for it to finish.

HTH

Thank you pullo for enlighten my mind :slight_smile: