I have been using JavaScript as a tool for many years now, but only recently have I begun programming applications with it. After watching Crockford on JavaScript – Level 6: Loopage I have begun to appreciate the Event Loop and the style of not blocking. To better get to grips with this I have gone back to an app where I am believe I have a badly designed area of code.
The application downloads an ~45KB JSON file (minified, uncompressed) containing ~20 elements, so on average each element has about 2.25KB of data. The download takes place every minute, as well as being manually triggered, at which point the new array replaces the old array. Every 15 seconds the DOM is cleared out and the array is iterated over. Calculations and logic are performed on the data to create groups of DOM elements to be inserted into the DOM.
Rather than doing:
for (int i = 0; i < array.length; i++) {
// Perform logic
}
How would I implement it in a none blocking fashion? So far I have come up with:
var performLogic = function performLogic(element) {
// Perform logic
}
var counter = 0;
var iterator = function iterator() {
counter += 1
if (counter < array.length) {
performLogic(array[counter]);
setTimeout(iterator, 0);
}
}
setTimeout(function() {
counter = 0;
iterator();
}, 0);
I can’t get my head around it. I know this will fail if the data was downloaded in between the performLogic() calls, as the array length may alter, regardless the group of data won’t be from the same array.
1 Answer