I have a javascript function that walks a tree recursively. It has two \"flag\" variables that are set to false or true above the scope of the function itself, and so if a f
Using timeouts to walk the tree, seriously? Have you considered to use iterative tree traversal instead of recursive?
Example:
var walkTree = function(node) {
var queue = [node];
while (queue.length) {
var n = queue.shift();
for (var i = 0; i < n.children.length; i++) {
queue.push(n.children[i]);
}
doSomethingWith(n);
}
}
Also see this so question and wikipeida article.
As alex vasi suggested, you might want to consider iterative tree traversal instead of recursive. However, if your dataset is huge and processing the data takes a lot of time, your UI may freeze. Thus, you still might want to do the processing asynchronously.
Here's a modification of alex's example:
function asyncIterativeWalkTree(node) {
var queue = [node];
var processQueue = function() {
var n = queue.shift();
for (var i = 0; i < n.children.length; i++) {
queue.push(n.children[i]);
setTimeout(processQueue, 0);
}
doSomethingWith(n);
}
processQueue();
}
The code snippet above does iterative traverse asynchronously, thus giving some time to the UI to update itself.
Here's a jsFiddle where you can notice the difference between synchronous and asynchronous traverse. The synchronous traverse makes your browser to freeze for a small period of time, while the asynchronous version gives browser some time to breath while processing the tree. (The code is a bit messy, sorry...)
Edit: Updated jsFiddle