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 =
Solution 1:
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.
Solution 2:
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();
}
Solution 3:
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.
Post a Comment for "Javascript For Loop Callback?"