wesbos
wesbos

Reputation: 26317

Javascript For loop callback?

Trying to think in Javascript rather than jQuery, so I'm wondering if I'm doing this right.

I want to have a callback when my loop is finished. Is this the proper way?

for(var i = 0; i < divs.length; i++) {

  /* do some stuff */ 

  if ( i === (divs.length - 1)) {  /* call back */  }

}

I should add that I don't mean something like a JSON request callback, just when the loop has finished.

Upvotes: 21

Views: 52745

Answers (3)

user489419
user489419

Reputation: 71

It seems to me the question is about the execution order of javascript code. And the answers are:

Yes you can put the callback outside because javascript code is executed line by line. In case of asynchonous ajax calls there might be other things to consider.

Upvotes: 6

codelahoma
codelahoma

Reputation: 904

For clarity, you should go with @mu's answer, but if you really must include the callback within the for construct, you can use the comma operator*:

for(var i = 0;
    i < divs.length || function(){ /* call back */ }(), false;
    i++) {

/* do some stuff */ 

}

*As explained in this fascinating article.

Upvotes: 24

mu is too short
mu is too short

Reputation: 434606

Why not say what you really mean and call the callback after the loop?

function thing_with_callback(divs, callback) {
    for(var i = 0; i < divs.length; i++) {
        /* do some stuff */ 
    }
    callback();
}

Upvotes: 22

Related Questions