2

I need to increment a var counter inside an $.each() loop. Here's my code:

ajaxCreateOrder = function(fileUrl, dataArray, numRecords) {
    var loopIteration = 1;
    var ajaxIterateDelay = 1000;
    $.each(dataArray, function(key,val) {
        setTimeout(function() {
            doAjaxRequest(loopIteration, fileUrl, val, numRecords);
        }, loopIteration * ajaxIterateDelay);
        loopIteration++;
    });
}

All is working as expected, except that loopIteration does not increment. What am I doing wrong? Thanks.

2 Answers 2

1

It is because of wrong use of a closure variable in loop

ajaxCreateOrder = function (fileUrl, dataArray, numRecords, storeView) {
    var ajaxIterateDelay = 1000;
    $.each(dataArray, function (index, val) {
        setTimeout(function () {
            doAjaxRequest(index + 1, fileUrl, val, numRecords);
        }, (index + 1) * ajaxIterateDelay);
    });
}

Assuming dataArray is an array, the first argument is the index, you can use it

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

3 Comments

It is because of wrong use of a closure variable in loop - It's just a simple multiplication to get the timeout for setTimeout. There is no variable which is evaluated when the loop has finished...
@Andreas loopIteration is used inside the setTimeout() which pauses a problem because it will have the last value of the loop
@Andreas problem solution
1
    setTimeout(function() {
        // ...
        loopIteration++;                   // inside
    }, loopIteration * ajaxIterateDelay);
                                           // not here

1 Comment

Thank you, that could be it :)

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.