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 :)

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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.
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.

Comments

0

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.