21

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.

3
  • 5
    Excuse my ignorance, but I don't understand it. If you want to call it when the loop is finished, why not calling after the loop instead of inside it? Commented Apr 9, 2011 at 2:08
  • If you're going to think in JavaScript, then do it. Do your loop, then call your function. Commented Apr 9, 2011 at 2:11
  • 1
    @Aleadam, because the loop might contain some asynchronous activities. E.g. You might be adding something to a database. This is my challenge anyhow... Commented Jan 7, 2019 at 7:24

3 Answers 3

24

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.

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

Comments

22

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();
}

5 Comments

because that would just be rediculous. plus what if you wanted to edit i interactively in a debugger?
Technically, that's not equivalent if the array is empty since it would still run. It's easy to work around though by adding an if statement.
@Matthew: The question was "I want to have a callback when my loop is finished." so putting the callback(); outside the loop is the only way and there is no need for a conditional on divs.length.
Yes, that's probably what he meant to do, but the example in the question wouldn't call the callback if divs.length is zero, because the for loop would never run. You're correct that putting the callback after the loop is almost certainly what he wanted though.
@Matthew: Yeah, there's some ambiguity involved so it could go either way. Hard to say what should happen when divs.length == 0 too.
6

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.

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.