How to Set a Delay in Ajax Call using JavaScript

In some rare cases, you need to delay the Ajax request for performing other tasks before receiving Ajax response. Using window setTimeout() method, you can set a delay in Ajax call for a specific time.

The setTimeout() method executes a function after some specified number of milliseconds. This function is ideal to make an Ajax call after a delay of few seconds.

The example code set 2 seconds delay in Ajax call using setTimeout() function.

$(function(){
    var delay = 2000;
    $('#element').on('click', function(){
        $.ajax({
            type: 'POST',
            url: 'https://www.codexworld.com',
            data: 'data_to_send',
            success: function(response){
                setTimeout(function() {
                    $('#target').append(response);
                }, delay);
            }
        });
    });
});

You can specify the delay time (in milliseconds) in delay variable as per your requirement.

Leave a reply

keyboard_double_arrow_up