This code works, but I'm sure it isn't written according to best practices for closures.  On the other hand, at least it's intuitive to me... the taskRunner object runs functions on setTimeout, so as not to block the UI for too long.  I'm breaking this function into chunks and running one chunk at a time.  I'm passing i into my function so it will be part of the closure, but I know I've seen this done more elegantly - I just can't wrap my head around how to do it right now.var tr = new taskRunner();        //I'm sure there's a better way to do a closure, but works        for(var i=0;i<blocks;i++){            var blockFunc = (function(i){                    var innerFunc = function(){                    var blockLen=Math.min(32768,len-(i*32768));                    stream.push(i==(blocks-1)?0x01:0x00);                    Array.prototype.push.apply(stream, blockLen.bytes16sw() );                    Array.prototype.push.apply(stream, (~blockLen).bytes16sw() );                    var id=imageData.slice(i*32768,i*32768+blockLen);                    Array.prototype.push.apply(stream, id );                }            return innerFunc;            }(i));            tr.AddTask(blockFunc);        }
Processing image blocks using a task runner
javascript;image;closure
IMO, inlined functions add clutter. I think it's clearer and cleaner to use a named function.function makeBlockFunc(i) {    return function(){        var blockLen=Math.min(32768,len-(i*32768));        stream.push(i==(blocks-1)?0x01:0x00);        Array.prototype.push.apply(stream, blockLen.bytes16sw() );        Array.prototype.push.apply(stream, (~blockLen).bytes16sw() );        var id=imageData.slice(i*32768,i*32768+blockLen);        Array.prototype.push.apply(stream, id );    };}Then invoke the function in the loop, passing i.var tr = new taskRunner();for(var i=0;i<blocks;i++){    tr.AddTask(makeBlockFunc(i));}Also, you didn't really need an inner and outer function. You could have done the .AddTask() directly. Here the returned function is added directly into the tr.