jQuery: AJAX response delay

When we develop an AJAX application we usually test it on our local web server first. However, this kind of test is not very reliable, because it doesn't take into account a possible delay that might occur when an AJAX transaction takes place. For testing purposes, it's useful to mimic such delay with our server-side language of choice. For example, here's a basic implementation in PHP:

header('Content-Type: text/plain');
echo 'Request complete!';

The sleep() function delays the execution of our script by taking an integer (seconds) as its only argument. So our AJAX request will receive a response after 3 seconds. Done that, we can build up our jQuery code:

function addMarks() {
    var html = $('#loader').html();
    var mark = '>';
    $('#loader').html(html + ' ' + mark);
     window.setTimeout(addMarks, 1000);

$(document).ready(function() {

    $('#response').ajaxStart(function() {
    $('#response').ajaxStop(function() {
    $('#run').click(function(e) {
     type: 'GET',
     url: 'delay.php',
     data: null,
     success: function(text) {


The addMarks() function has only a demonstrative purpose (you can use an AJAX spinner here) and simply adds a character to our AJAX loader after 1 second. So there will be three characters when our transaction is complete. Note that here we've used .ajaxStart() and .ajaxStop() for showing and hiding our loader. You can see this example here.

One thought on “jQuery: AJAX response delay”

  1. Thanks! For some reason I started over complicating this in my head thinking that maybe I'd have to configure Apache to serve things up slower or something. "Sleep()" would do it though...

Leave a Reply

Note: Only a member of this blog may post a comment.