How is the JSLint function-inside-loop applied when using jQuery.each ()?

I use the jQuery .each() call, which uses an anonymous function from the for loop. JSLint offers the warning "Do not execute functions in a loop."

Here is a piece of code from a larger function - in fact, it checks to see if all the players in the game are โ€œaliveโ€ (has at least one part on the board).

 for( i=0 ; i<PLAYERLIMIT ; ++i ) { if( player[i].status !== 0 ) { //skip already dead players var stillAlive = false; $board.find("td").each( function() { //this func causes JSLint warning if( $(this).data("owner") === player[i].number ) { stillAlive = true; return false; } }); if( !stillAlive ) { //... action to take for dead players } } } 

I see how to remove this warning - just declare the function separately and call it. But this is a very small one-shot function, and essentially I consider this body of a nested for loop (I essentially read the .each() call as something like for $("td") in $board {} )

Is this JSLint one of those style warnings, or is it more serious?
Basically, is it better for me to fix this?

I would like to understand the reason for the warning, so any RE comments on why the warning exists would be helpful (again, I want to know if this is practical or style).

+4
source share
2 answers

This is just a style, mainly, probably some efficiency obtained in IE, although new JS engines will in any case integrate the function through their tracing mechanism. You can get rid of the JSLint "error" like this:

 function setupPlayer(player) { var stillAlive = false; $board.find("td").each( function() { if( $(this).data("owner") === player.number ) { stillAlive = true; return false; } }); if( !stillAlive ) { //... action to take for dead players } } for(var i=0 ; i<PLAYERLIMIT ; ++i ) { if( player[i].status !== 0 ) { //skip already dead players setupPlayer(player[i]); } } 

Do you have to? Personally, I would ignore it in this case for the convenience of maintenance, for me the current version is much easier to read / maintain. Your call is here, which version is best for you? In any case, this is likely to have little effect on performance.


Bit tangent but related:
What has a greater impact on performance is caching the <td> selector, bypassing the DOM is quite expensive. I would do this before your for loop:

 var cells = $board.find("td"); 

And use cells inside the loop, no need to search for the same elements again :)

+3
source

So, I find that JSLint is worried about something like this:

 for (var i=0; i<10; i++) { $("#my-elem" + i.toString()).click(function() { alert(i)}); } 

This will lead to the fact that all elements with the identifiers my-elem0 - my-elem9 will warn "10" when pressed - i attached to the containing function, and not to the for tag. JSLint tries to protect you from this by telling you not to do functions in a loop. It is not smart enough to know that each will call your function now, not later.

+3
source

All Articles