title: Understanding Event Queue and Call stack in javascript
body: <p>My curiosity for understanding the concept of "Event Queue" and "Call Stack" Started when I was solving this question:</p>
  
  <pre><code>var list = readHugeList();
  
  var nextListItem = function() {
      var item = list.pop();
  
      if (item) {
          // process the list item...
          nextListItem();
      }
  };
  </code></pre>
  
  <p><strong>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?</strong> </p>
  
  <p>The solution that was mentioned was this:</p>
  
  <pre><code>var list = readHugeList();
  
  var nextListItem = function() {
      var item = list.pop();
  
      if (item) {
          // process the list item...
          setTimeout( nextListItem, 0);
      }
  };
  </code></pre>
  
  <p><strong>Solution:</strong></p>
  
  <blockquote>
    <p>The stack overflow is eliminated because the event loop handles the
    recursion, not the call stack. When nextListItem runs, if item is not
    null, the timeout function (nextListItem) is pushed to the event queue
    and the function exits, thereby leaving the call stack clear. When the
    event queue runs its timed-out event, the next item is processed and a
    timer is set to again invoke nextListItem. Accordingly, the method is
    processed from start to finish without a direct recursive call, so the
    call stack remains clear, regardless of the number of iterations.</p>
  </blockquote>
  
  <p><strong>Now my question:</strong></p>
  
  <p>Q1) What is the difference between "Event Queue" and "call stack"</p>
  
  <p>Q2) I did not understand the answer. Can someone explain me in detail?</p>
  
  <p>Q3) <strong>When I execute a function or call a variable or object in javascript. How does the flow go?</strong> <strong>What goes in call stack?</strong> (Let's say I do setTimeout.. Does it go to callstack or event queue?)</p>
  
  <p>These concepts are very unclear. I googled but most of the results aren't what I was expecting to understand.</p>
  
  <p>Please help!</p>