title: Maintaining a fixed number of items in a dynamic 'list' of items using jQuery
body: <p>I am trying to write a small demo which will maintain a fixed number of items in a list which is being constantly updated.</p>
  
  <p>This is my very first attempt at using jQuery, so I would appreciate feedback on if I can improve the code (almost surely!) and also, I am stuck on the last function <strong><em>truncateItems()</em></strong> and would appreciate some help on how to implement it.</p>
  
  <p>Here is what I have written so far:</p>
  
  <pre><code>&lt;html&gt;
  &lt;head&gt;
  &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"&gt;&lt;/script&gt;
  &lt;/head&gt;
  &lt;body&gt;
      &lt;div&gt;
         &lt;div id="container"&gt;&lt;/div&gt;
      &lt;/div&gt;
  &lt;/body&gt;
  &lt;script type="text/javascript"&gt;
  /* &lt;![CDATA[ */
  var maxitems = 10;  // maximum number of items in container
  
  function generateItems(){
      var min = 0;
      var max = 10;
      var items = '';
  
      var randnum = Math.floor(Math.random() * (max - min + 1)) + min;
  
      for (i=0; i &lt; randnum; i++){
          if (i) 
              item += '\n&lt;div class="item"&gt;Item number: ' + i + '&lt;/div&gt;';
          else
              item = '&lt;div class="item"&gt;Item number: ' + i + '&lt;/div&gt;';
      }
  
      addItems(items);
      truncateItems(items);
  
      window.setTimeout(generateItems, 1000)
  }
  
  function addItems(items){
      return items + '\n' + $("#container").text(); 
  }
  
  function truncateItems(items){
      //Need to return the first N elements
      //Need to either parse items or iterate over them whilst building a new string ? ...
  }
  
  
  $(document).ready(function(){
      window.setTimeout(generateItems, 5000); // wait for 5 secs before starting updates
  });
  
  /*]]&gt; */
  &lt;/script&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p>In case what I am trying to do is not clear from the code above, this is what I'm trying to do:</p>
  
  <ol>
  <li>Generate a random number of items</li>
  <li>Update the 'list' of items (held in element with id 'container'). The update should be done so that the latest generated data are placed BEFORE the older items that were in the list (so visually, they appear 'on top')</li>
  <li>Ensure that element with id 'container' has no more than 10 items in it at any time - with only the LATEST (i.e. TOPMOST) 10 items being left in the 'list'</li>
  </ol>