Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript For loop callback?

Tags:

javascript

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.

like image 798
wesbos Avatar asked Apr 09 '11 02:04

wesbos


People also ask

What is callback () in JavaScript?

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.

Is JavaScript callback asynchronous?

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 .

How does JavaScript event loop work?

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.


3 Answers

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.

like image 119
codelahoma Avatar answered Oct 23 '22 09:10

codelahoma


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();
}
like image 31
mu is too short Avatar answered Oct 23 '22 08:10

mu is too short


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.

like image 6
user489419 Avatar answered Oct 23 '22 08:10

user489419