how to make this synchronous recursive function asynchronous

后端 未结 2 1126
一整个雨季
一整个雨季 2021-01-05 14:31

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

相关标签:
2条回答
  • 2021-01-05 15:03

    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.

    0 讨论(0)
  • 2021-01-05 15:06

    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

    0 讨论(0)
提交回复
热议问题