Reputation:
I have the following function in my code. Here's a simplified version:
$.ajax({
url: $form.attr('action'),
dataType: 'json',
type: 'POST',
data: $form.serializeArray(),
success: function (json, textStatus, XMLHttpRequest) {
// delay here
alert("hello");
}
Is there some way that I can introduce a delay. For example a delay of 5 seconds into the above code?
Note that I need to replace the words // delay here with something that can give a delay if possible.
Upvotes: 2
Views: 168
Reputation: 708136
You would use setTimeout()
and this is how you would introduce it into your own code:
$.ajax({
url: $form.attr('action'),
dataType: 'json',
type: 'POST',
data: $form.serializeArray(),
success: function (json, textStatus, XMLHttpRequest) {
// save 'this' pointer in case you need it in the setTimeout() function
// because it will be set to something different in the setTimeout() callback
var self = this;
setTimeout(function() {
// execute whatever code you want here with a 5 second delay
alert("hello");
}, 5000) ;
}
Upvotes: 2
Reputation: 196296
You can use the setTimeout
method
if you want to delay the alert just use
success: function (json, textStatus, XMLHttpRequest) {
// delay here
setTimeout(function(){alert("hello");}, 5000); // 5000 is in milliseconds
}
Upvotes: 1
Reputation: 9706
Sure you can.
$.ajax({
url: $form.attr('action'),
dataType: 'json',
type: 'POST',
data: $form.serializeArray(),
success: function (json, textStatus, XMLHttpRequest) {
// delay here
setTimeout(function() { alert("hello"); }, 5000);
});
Upvotes: 3
Reputation: 163602
You can use setTimeout()
with an anonymous function:
setTimeout(function() { /* your code here */ }, 5000);
This will run the code within that function after a 5-second delay.
Upvotes: 6