title: Javascript asynchronous for loop
body: <p>Is there a way for me run codes asynchronously in a for loop? </p>
  
  <p>In this example, events from day <strong>x</strong> to <strong>y</strong> are required to be added into the calendar through a for loop. However the loop is taking roughly a min and its too long, as it is required to go through and add all the days from Jan 4, 2016 to Dec 28, 2020. </p>
  
  <p>Right now, I will have to wait for all the days to be loaded to view the result.
  Is there a way for events to get added and appear as soon as the 'addEventSource' is fired / before it goes through all the whole loop. Is it possible to make it asynchronous?</p>
  
  <p>Javascript</p>
  
  <pre><code>$(document).ready(function () {
          loadCalendar(null);
          var start = new Date("Jan 4, 2016 08:00:00");
          var end = new Date("Dec 28, 2020 12:00:00");
          var startTime = new Date("Jan 4, 2016 08:00:00");
          var endTime = new Date("Jan 4, 2016 12:00:00");
  
          addCalendarEvents("Test", start, end, startTime, endTime);
      });
  
  function addCalendarEvents(title, start, end, repeatDays, startTime, endtime) {
          var events = [];
  
          var one_day = (24 * 60 * 60 * 1000);
          var loopEnd = end.getTime();
  
          for (var loop = start.getTime() ; loop &lt;= loopEnd; loop = loop + one_day) {
              var eventDate = new Date(loop);
  
                  var tempStart = start;
                  var tempEnd = end;
  
                  tempStart.setDate(eventDate.getDate());
                  tempStart.setMonth(eventDate.getMonth());
                  tempStart.setFullYear(eventDate.getFullYear());
                  tempEnd.setDate(eventDate.getDate());
                  tempEnd.setMonth(eventDate.getMonth());
                  tempEnd.setFullYear(eventDate.getFullYear());
  
                  $('#calendar').fullCalendar('addEventSource', [{
                      title: title,
                      start: tempStart,
                      end: tempEnd,
                      allDay: false
                  }]);
  
          }
      }
  </code></pre>
  
  <p>p.s. <code>$('#calendar').fullCalendar('addEventSource', event) adds events to the calendar.</code></p>