Splitting Javascript Loops

There’s a programming trick, I was unaware of so I thought I’d share…

In Javascript for example, it’s single threaded. Which means you don’t want to do something like this:

for(var i =0; i < 1000000; i++) {
  // do lots of stuff
}

That’s because Javascript will try and complete the process all at once, meaning your page will hang while it’s trying to complete the process.

But you could do:

for(var i = 0; i < 1000; i++) {
  setTimeout(function(){
    for(var x = 0; x < 1000; i++) {
      // do spme stuff
    }
  }, 0)
}

This allows the browser to effectively “catch up” before it starts on the next batch. To make this into a function you could do

function part(array, callback) {
  setTimeout(function(){
    var i = array.shift();
    callback.call(i);

    if(array.length > 0) {  
      setTimeout(arguments.callee, 0);
    }
  }, 0);
}

This function from here, will set timeouts in order to process your array, but it’s the same concept. You pass an array and a function (your definition of what to do on each item in the array) as a variable to “part()” and it will process things according to when the browser has the next available tick

Pretty cool

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.