0

How's it going,

Need some assistance, with some for loop and pausing. I did some research myself and I keep running into setTimeout() function but I need help understanding it more or if someone can help me out with how to implement it into my code or if there's another way.

    $(document).ready(function() {
            for(i=0; i<counter; i++)
            {
                dataCounter = i;
                $.ajax({
                  url: 'file.php',
                    dataType: 'json',
                    data: {count: dataCounter},
                    error: function(){
                        alert('Error loading XML document');
                    },
                    success: function(data){
                        $("#contents").html(data);  
                    }
                });
            }

});

I would like to know how to pause after my $.ajax function before going on to my next increment.

Please help! Thank you :)

hellomello
  • 8,219
  • 39
  • 151
  • 297

3 Answers3

2

What about...

(function() {

    var index = 0;

    function next() {

        setTimeout(function() {
            if (index == counter) {
                return;
            }

            // Do what you need to do   
            index++;
            next();
        }, 1000);

    }

})();

Alternatively, you can make a sleep style function with Date and a do { ... } while() loop. But the setTimeout() is much better, because any JavaScript sleep style function has to sit around looping until it is ready to finish, which isn't really sleeping.

Community
  • 1
  • 1
alex
  • 479,566
  • 201
  • 878
  • 984
  • can I just copy the .ajax function into where you say // Do what you need to do, and this will work? Also, do I just put the (function() {...})(); all in the $(document).. sorry I'm fairly new to jquery. – hellomello May 01 '11 at 05:01
2

You mean "wait the request finish to send the next" ?

If so, set one more parameter in .ajax call.

async: false

From jQuery .ajax doc

async :: Boolean - Default: true

By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false. Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active.

BrunoLM
  • 97,872
  • 84
  • 296
  • 452
0

http://jsfiddle.net/samccone/hkjpA/

Hi andrewliu this example should work just fine, Hope that this help you

samccone
  • 10,746
  • 7
  • 43
  • 50