title: Javascript + Run a function for X seconds
body: <p>Is there any way to run my function within 5 seconds in <code>Javascript</code>?</p>
  
  <p>For example if I have <code>Function A</code> and <code>Function B</code>. I want to run <code>Function A</code> for 5 seconds, just after it, it will run <code>Function B</code>. </p>
  
  <ul>
  <li>IF <code>Function A</code> only takes 1 second to finish the process, then it only need to wait another 4 seconds. </li>
  <li>But if <code>Function A</code> takes 3 seconds to finish, then it would need another 2 seconds to wait, before processing <code>Function B</code></li>
  <li>IF <code>Function A</code> takes more than 5 seconds, then B needs to wait until A finish its job, until it can start its job. (edited)</li>
  </ul>
  
  <p>Right now, im using Sleep Function that I found not long time ago</p>
  
  <pre><code>function wait(ms){
     var start = new Date().getTime();
     var end = start;
     while(end &lt; start + ms) {
       end = new Date().getTime();
    }
  }
  
  wait(5000);
  </code></pre>
  
  <p>But with this code, it will need to wait for 5 seconds no matter how much time <code>Function A</code> needs to finish its process.</p>
  
  <p><strong>EDIT</strong> </p>
  
  <p><code>Function A</code> does an <code>AJAX POST</code> call. which makes it takes different time to finish its job.</p>
  
  <p>This question is different from <a href="https://stackoverflow.com/questions/951021/what-is-the-javascript-version-of-sleep">What is the JavaScript version of sleep()?</a> because :</p>
  
  <ol>
  <li>this is going to be used in IE which doesn't support promise (as I read)</li>
  <li>If I use settimeout, and A takes longer than 5 seconds, then B will fire it function first without waiting A to finish.</li>
  </ol>