Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better way to seize values inside loops

for( var i=0; i<20; i++) 
    setTimeout(function(){ 
        console.log(">>> "+i); 
    }, i*100);

So, the code above outputs >>> 19 20 times. To keep i at it's iteration value I'm using a closure:

for(var i=0; i<20; i++)(function(i){
    setTimeout(function(){ 
        console.log(">>> "+i); 
    }, i*100);
}(i));

What's the problem? The problem is loop control statements, continue; I can do with return; but for those times when I need break; code gets counter-intuitive when others try to read it.

So what can I do?

like image 330
Silviu-Marian Avatar asked Jul 20 '12 00:07

Silviu-Marian


1 Answers

How about this?

for (var i = 0; i < 20; i++) {
    var action = (function(i){
        setTimeout(function(){ 
            console.log(">>> "+i); 
        }, i*100);

        // break => return false
        // continue => return anything (e.g. true)
        // default => return nothing
        return false;
    })(i);

    if (action !== undefined) {
        if (!action) {
            break;
        }
        else {
            continue;
        }
    }
}

EDIT:
Added "support" for continue statement. This now works somehow like the jQuery.each() loop.

like image 89
Aletheios Avatar answered Oct 18 '22 11:10

Aletheios