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;
            type: "POST",
            url: "search.php",
            data: p,
	    beforeSend: function() {
		$('#loader').show(); //show image loader
	    success: function(data){