Search code examples
jqueryajaxfor-loopdelaysettimeout

using for loop in jquery then pause between each iteration help


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


Solution

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