How does setTimeout prevent potential stackoverflow

后端 未结 2 376
伪装坚强ぢ
伪装坚强ぢ 2021-01-22 08:58

An example :

var list = readHugeList();

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

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


        
2条回答
  •  猫巷女王i
    2021-01-22 09:34

    Think of setTimeout(, 0) to schedule a function to run after this one terminates. nextListItem() will not be recursively called, but called again by the JS environment.

    If you do var r() = function() { r(); }; the function calls itself and will overflow the stack. If you do var r() = function() { setTimeout(r, 0); }; then r() will be scheduled to run after r() terminates and it will run forever.

    The is a reason to use setTimeout(, 0) instead of while or for to loop over the list. It allows the browser to process other events before the next call to nextListItem. If the list is long, this avoids blocking the browser for a long time. On the other hand, if nextListItem is manipulating the DOM, it is much slower than doing it in one slew.

提交回复
热议问题