04.11.2015 Views

javascript

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 18: Advanced Techniques<br />

When you find a loop is taking a significant amount of time to complete, and you can answer “ no ” to<br />

either of the previous two questions, you can split the loop using timers. This is a technique called array<br />

chunking , whereby processing of the array happens in small chunks, most often one at a time. The basic<br />

idea is to create a queue of items to process, use timers to pull the next item to process, process it, and<br />

then set another timer. The basic pattern looks like this:<br />

setTimeout(function(){<br />

//get next item and process it<br />

var item = array.shift();<br />

process(item);<br />

//if there’s more items, set another timeout<br />

if(array.length > 0){<br />

setTimeout(arguments.callee, 100);<br />

}<br />

}, 100);<br />

In the array chunking pattern, the array variable is essentially a “ to do ” list of items to process. Using<br />

the shift() method, you retrieve the next item in the queue to process and pass it in to a function. If<br />

there are still items in the queue, then another timer is set, calling the same anonymous function via<br />

arguments.callee . You can accomplish array chunking easily, using the following function:<br />

function chunk(array, process, context){<br />

setTimeout(function(){<br />

var item = array.shift();<br />

process.call(context, item);<br />

}<br />

if (array.length > 0){<br />

setTimeout(arguments.callee, 100);<br />

}<br />

}, 100);<br />

The chunk() method accepts three arguments: the array of items to process, a function to use to process the<br />

items, and an optional context in which to run the function. Inside the function is a duplication of the basic<br />

pattern described previously, with the process() function being called via call() so that a proper context<br />

can be set if necessary. The interval of the timers is set to 100 milliseconds, which gives the JavaScript<br />

process time to go idle between item processing events. This interval can be changed based on your needs,<br />

although 100 milliseconds works well in most cases. The function can be used as follows:<br />

var data = [12,123,1234,453,436,23,23,5,4123,45,346,5634,2234,345,342];<br />

function printValue(item){<br />

var div = document.getElementById(“myDiv”);<br />

div.innerHTML += item + “ < br > ”;<br />

}<br />

chunk(data, printValue);<br />

This example outputs each value in the data array to a < div > element by using the printValue()<br />

function. Since the function exists in the global scope, there ’ s no need to pass in a context object<br />

to chunk() .<br />

603

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!