0

So JSHint tells me I should not make functions within a loop. I then usually make a function outside the loop.

But now I have a part where this is more difficult:

for (r=0;r<x;r++) {
    for (c=0;c<y;c++) {
        var arr = [c,r];
        setTimeout( (function(arr) { return function() { doSomething(arr); };})(arr), 50+c*550 + r*230 );
    }
}

how could i refactor this part to not get the JSHint warning?

clamp
  • 33,000
  • 75
  • 203
  • 299
  • I don't think an answer can be given without providing more context. Where is y defined? What is this snipped doing, and why are you executing settimout in a loop (which looks like a code smell in itself)? – helpermethod Jul 06 '12 at 08:48
  • x and y are just some integer variables. what is bad about setTimeouts in a loop? – clamp Jul 06 '12 at 08:57

1 Answers1

5

It is simple:

for (r=0;r<x;r++) {
    for (c=0;c<y;c++) {
        var arr = [c,r];
        setTimeout( proxy(arr), 50+c*550 + r*230 ); 
    }
}

function proxy(arr){
    return function(){
        doSomething(arr);
    };
}
Engineer
  • 47,849
  • 12
  • 88
  • 91