jQuery Ajax call

Hi,

I have a function that displays a loading icon just before the ajax call starts, but I wanted to display that icon only if the ajax call takes longer than 3 seconds. My question is: How to implement a counter after the ajax call?


function search() {
	var val = $("#sfield").val(); 
	var p = "sfield=" + val;
	$.ajax({
            type: "POST",
            url: "search.php",
            data: p,
	    beforeSend: function() {
		$('#loader').show(); //show image loader
	    },
	    success: function(data){
	        $('#loader').hide();
                $('#sresults').html(data);
            }
    });
}

You can use the setTimeout() function to trigger something to happen after a delay:


function search() {
	var val = $("#sfield").val(); 
	var p = "sfield=" + val;
	$.ajax({
            type: "POST",
            url: "search.php",
            data: p,
	    beforeSend: function() {
		$('#loader').show(); //show image loader
                setTimeout(function(){
                     if ($('#loader').is(':visible')) {
                         // Show a different icon
                     }
                },3000);
	    },
	    success: function(data){
	        $('#loader').hide();
                $('#sresults').html(data);
            }
    });
}

Works like a charm, thanks Anthony!