title: Javascript : Do Action after elapsed time
body: <p>I have a page where I fire an ajax request AND show a loading sign for the first 6 seconds after the user presses a button :</p>
  
  <pre><code>&lt;button onclick="runLoader();"&gt;&lt;/button&gt;
  
  &lt;script&gt;
      var startTime=(new Date).getTime();
      function runLoader(){
          runAjax();
          var i=0;
          var timer = setInterval(function(e){
              i++;
              //code for loading sign
              if(i==3)
                  clearInterval(timer);
          } ,2000);
      }
  
      function runAjax(){
          $.ajax({
              //
          }).done(function(){
              var timer2 = setInterval(function(){
                  var d = new Date();
                  var t = d.getTime();
                  if(t-startTime&gt;=6000){
                      clearInterval(timer2);
                      // do X
                  }
              },500);
          }
      }
  &lt;/script&gt;
  </code></pre>
  
  <p>I want to do action <strong>X</strong> only after both <code>runLoader()</code> has run for 6 seconds and <code>runAjax()</code> has resulted in a response, and no sooner. </p>
  
  <p>Like, if runAjax() responds in 2 seconds, I still want to continue showing loading sign for 6 seconds and then perform <strong>X</strong>. 
  And if the loading sign has shown for 6 seconds, I want to wait for runAjax() to return for as long as it takes. </p>
  
  <p>But using the <code>Date()</code> method is giving inaccurate results. For eg : It shows 7.765 s elapsed even when only 2 s have passed. I read somewhere I should use <code>console.log(time)</code> for better accuracy, but it doesnt work in &lt;=IE9.</p>
  
  <p>Is there a better way to approach this problem ?</p>
  
  <p><strong>Note:</strong> I am using <code>setInterval()</code> instead of <code>setTimeout()</code> because the loading involves cycling through an array of 3 elements, "Fetching", "Processing" and "Loading" each shown for 2 seconds :)</p>