title: JavaScript: I am trying to use a setInterval() function to generate one message every 3 seconds
body: <p>Currently I am running a setInterval() funnction to populate a div with new messages and I am attempting it to populate one at a time, however my current setInterval() is generating multiple at a time. How can I fix this?</p>
  
  <p>Here's my code snippet:</p>
  
  <pre><code>function newMessage(){
              // Loop goes through emails and creats divs for subject, date, sender, and body
           for(var i = 0; i &lt; window.geemails.length; i++ ) {
  
              //email container
              var div = document.createElement("div");
  
              //date
              var dateField = document.createElement("h1");
              dateField.className = "date";
              dateField.innerHTML = window.geemails[i].date;
              div.appendChild(dateField);
  
              //subject
              var subjectField = document.createElement("h1");
              subjectField.className = "subject";
              subjectField.innerHTML = window.geemails[i].subject;
              div.appendChild(subjectField);
  
              //sender
              var senderField = document.createElement("h1");
              senderField.className = "sender";
              senderField.innerHTML = window.geemails[i].sender;
              div.appendChild(senderField);
  
              //body
              var bodyField = document.createElement("p");
              bodyField.className = "body";
              bodyField.innerHTML = window.geemails[i].body;
              div.appendChild(bodyField);
  
              //Separate message content into containers
              document.getElementById("main").appendChild(div);
  
              //inbox counter
              document.getElementById('counter').innerHTML = "You have " + window.geemails.length + " messages";
  
  
           }
  
      }
  
  
          newMessage();
  
  
  
          //interval for loading new messages
          function addNewMessage() {
              setInterval(function(){window.geemails.push(getNewMessage());newMessage();}, 3000);
          }
  
          addNewMessage();
  </code></pre>