使用setTimeout函数解决栈溢出问题

下面的代码,如果队列太长会导致栈溢出,怎样解决这个问题并且依然保持循环部分:

var list = readHugeList();
var nextListItem = function() {
    var item = list.pop();
    if (item) {
        // process the list item...
        nextListItem();
    }
};

通过修改nextListItem功能可以避免潜在的堆栈溢出,如下所示:

var list = readHugeList();

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

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

栈溢出主要是因为循环事件,而不是栈。当执行nextListItem时,如果item不是null,在settimeout函数中的nextListItem会推入到事件队列中。当事件空闲,则会执行nextListItem,因此,这种方法从开始到结束没有直接进行循环调用,可以不用考虑循环次数。

关于setTimeout函数想要了解更多,可以参考 你应该知道的setTimeout秘密(原文)

原文地址:https://www.cnblogs.com/guorange/p/7219171.html