How to give timeout into ajax loader?

Viewed 435

I have problem with added a timer for loader,
I want the loader to take longer to call the function.

I have $.ajaxSetup for loaded a loader like this

a.ajaxSetup({
headers: {"X-CSRF-TOKEN": a('meta[name="csrf-token"]').attr("content")},

beforeSend: function(){
    a('.page-overlay').addClass("loading");
},
complete: function() {
  a('.page-overlay').removeClass("loading");
},
});

Then I have calling the $.ajaxSetup like this:

a(document).on('click', 'a#details_transactions', function(e){
var d = a(this).data('pid'),
    s = a('#CallModal'),
    w = a('.modal-content');
  e.preventDefault(),
    a.post(transaction_details,{_token: csrf_token, pid: d}).done((e) => {
      s.modal('show');console.log(e);w.html(e)
    }).fail((e)=>{s.modal('hide');Toast.fire({icon: 'error',title: 'Something Wrong. Please try again!'})});
 });

If like this, How do I add a timer to make the loader look taking long to load?

Edited

I have try using setTimeout in between

s.modal('show');console.log(e);w.html(e)

Then

 setTimeout(function() {
 s.modal('show');console.log(e);w.html(e)
 },2000)

But remove loader show after timeOut.
I think problem with .done because this calling after .done function.

So, Should I use $.ajax with success: for give a timer ?

1 Answers

So you have $.ajaxSetup() which applies on all ajax request you may have...

But for the below specific request, you want the loader to be delayed.

I think your solution will be to use the global parameter in that $.post() to avoid $.ajaxSetup() to trigger on that one.

Whether to trigger global Ajax event handlers for this request. Ref.

So you can manage that .loading differently here, without affecting the rest.

a(document).on('click', 'a#details_transactions', function(e){
  e.preventDefault();
  
  var d = a(this).data('pid'),
      s = a('#CallModal'),
      w = a('.modal-content');
    
  a('.page-overlay').addClass("loading");  // add the loading class here
  
  // Notice the global: false here!
  a.post({
    url: transaction_details,
    data: {_token: csrf_token, pid: d},
    global: false
  }).done((e) => {
  
    // Use the setTimeout here
    setTimeout(function(){
      s.modal('show');console.log(e);w.html(e);
      a('.page-overlay').removeClass("loading");  // remove the loading class here
    },2000);

  }).fail((e)=>{
    s.modal('hide');
    a('.page-overlay').removeClass("loading");  // remove the loading class here too!
    Toast.fire({icon: 'error',title: 'Something Wrong. Please try again!'})
  });
});
Related