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.
A callback is a function passed as an argument to another function. This technique allows a function to call another function. A callback function can run after another function has finished.
Callbacks are not asynchronous by nature, but can be used for asynchronous purposes. In this code, you define a function fn , define a function higherOrderFunction that takes a function callback as an argument, and pass fn as a callback to higherOrderFunction .
The Event Loop has one simple job — to monitor the Call Stack and the Callback Queue. If the Call Stack is empty, the Event Loop will take the first event from the queue and will push it to the Call Stack, which effectively runs it. Such an iteration is called a tick in the Event Loop.
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.
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();
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With