首页 > 其他 > 详细

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

时间:2017-07-21 19:36:16      阅读:260      评论:0      收藏:0      [点我收藏+]

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

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函数解决栈溢出问题

原文:http://www.cnblogs.com/guorange/p/7219171.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!