在递归函数中处理大数组时堆栈溢出

时间:2015-07-06 15:41:16

标签: javascript

如果数组列表太大,为什么以下递归代码会导致堆栈溢出?我该如何解决这个问题仍然保留递归模式?

var list = readHugeList();

var nextListItem = function() {
    var item = list.pop();

    if (item) {
        // process the list item...
        nextListItem();
    }
};

3 个答案:

答案 0 :(得分:4)

这听起来很奇怪,但请使用setTimeout

像这样:

//fill it with 50000 elements
var list = Array(50001).join('1.1').split('.');

var nextListItem = function() {
    var item = list.pop();

    if (item) { //should be list.length

        // recursion here!
        setTimeout( nextListItem, 0 );

    }
};
nextListItem();

递归现在无穷无尽

请注意,某些浏览器不喜欢那里的0 作为副作用,您的代码不会阻止浏览器。

答案 1 :(得分:0)

好像你只是循环遍历一个数组。您是否尝试过使用简单的for循环?

var list = readHugeList();
for (var i = 0; i < list.length; i++) {
    //Do something with list[i]
}

答案 2 :(得分:0)

var taskList = breakBigTaskIntoMicroTasks(monsterTaskList);

// requestAnimationFrame will get executed in each 16ms of duration.
requestAnimationFrame(processTaskList);

function processTaskList(taskStartTime) {
    var taskFinishTime;

    do {
        // Assume the next task is pushed onto a stack.
        var nextTask = taskList.pop();

        // Process nextTask.
        processTask(nextTask);

        // Go again if there’s enough time to do the next task.
        taskFinishTime = window.performance.now();
       } while (taskFinishTime - taskStartTime < 3);
        if (taskList.length > 0)
            requestAnimationFrame(processTaskList);

}