Reham Fahmy
Reham Fahmy

Reputation: 5063

how to delay ajax respond for number of seconds

I'm loading some results via jQuery ajax in a div container. I would like the results to be shown to the user after a 2 seconds delay

I'm using the following code

<script type="text/javascript">
$(function() {
    $("#submit").click(function() {
        $('#myform').slideToggle('#loading');
        $('#loginhandle').show("slow");
        var name = $("input#name").val();
        var age = $("input#age").val();
        var dataString = 'name='+ name + '&age=' + age ;
        $.ajax({
            type: "POST",
            url: "results.php",
            data: dataString,
            success: function(msg) {
                $('#loading').slideToggle('#results');
                $('#results').show("slow");
                $('#results').html(msg)
                .hide()
                .fadeIn(1500, function() {
                });
            }
        });
        return false;
    });
});
</script>

Results shown at contianer

<div id='loading' style='display:none'>
Please wait for while
</div>

<div id='results' style='display:none'>
<div id='results' class='results'></div>
</div>

i made change on the code at this part

$('#loading').slideToggle('#results');

to

setTimeout(function() {
    $('#loading').slideToggle('#results');
}, 2000);

but it only delays the loading container so results are shown while it saying 'please wait' so how i can delay it?

Upvotes: 0

Views: 105

Answers (3)

marcyb5st
marcyb5st

Reputation: 252

to achieve the wanted result you should change the code in

setTimeout(function() {
   $('#loading').slideToggle('#results');
   $('#results').show("slow");
   $('#results').html(msg)
}, 2000);

The reason is that setTimeout delays only the code include in the closure you pass as a parameter.

Upvotes: 1

keeehlan
keeehlan

Reputation: 8054

All you'll have to do is modify your success callback:

success: function(msg) {
    setTimeout(function() {
        $('#loading').slideToggle('#results');
        $('#results').show("slow");
        $('#results').html(msg).hide().fadeIn(1500, function() {

        });
    }, 2000);
}

Upvotes: 2

Trevor
Trevor

Reputation: 16116

Correct me if I am misunderstanding but to delay everything just put all the success function code in your setTimeout function.

success: function(msg) {
   setTimeout(function() {
     $('#loading').slideToggle('#results');
     $('#results').show("slow");
     $('#results').html(msg).hide().fadeIn(1500, function() {

     });}, 2000);      
 });

Upvotes: 3

Related Questions