setTimeout如何防止潜在的stackoverflow [英] how does setTimeout prevent potential stackoverflow

查看:110
本文介绍了setTimeout如何防止潜在的stackoverflow的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个例子:

var list = readHugeList();

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

    if (item) {
        setTimeout( nextListItem, 0);
        // ^^^^^^^^ this line
    }
};

如何使用setTimeout来防止潜在的堆栈溢出?我理解事件队列的概念以及堆栈,但我很难连接两者。

How does use of setTimeout prevent potential stackoverflow here? I understand concept of event queue as well as stack, but I'm having difficulty connecting the two.

推荐答案

设置超时不会导致堆栈溢出,因为它是异步的。它只会将回调放到事件队列中而不会阻止执行。


在第一种情况下:

setTimeout只是将回调放入事件队列,而父函数在没有占用堆栈的情况下退出。

即使超时是0毫秒,它也会在下一个事件循环中调用,因此不会阻止执行中的代码

setTimeout just puts the callback to event queue and the parent function exits after without busying the stack.
Even though the timeout is 0 ms, it will be called in the next event loop, thus not blocking the code in execution

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

    if (item) {
         setTimeout( nextListItem, 0);
    }
};

在第二种情况下:


Parent调用子函数将新条目放入堆栈,即使父项未从堆栈中清除。

最终更多的递归调用会使堆栈失效。

In the second case:

Parent call the child function putting new entry into stack, even though the parents is not cleared from the stack.
Eventually more recursive calls would blow the stack.

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

        if (item) {        
           nextListItem();
        }
    };

这篇关于setTimeout如何防止潜在的stackoverflow的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆