1. The following recursive code will cause a stack overflow if the array list is too large. How can you fix this and still retain the recursive pattern?
|
var list = readHugeList();var nextListItem = function() {<br> var item = list.pop(); if (item) {<br> // process the list item...<br> nextListItem();<br> }<br>}; |
Answer:The potential stack overflow can be avoided by modifying the nextListItem function as follows:
|
var list = readHugeList();var nextListItem = function() {<br> var item = list.pop(); if (item) {<br> // process the list item...<br> setTimeout( nextListItem, 0);<br> }<br>}; |
The stack overflow is eliminated because the event loop handles the recursion, not …
JavaScript Interview Questions (Part-2) Read More »