pause until event/function is completed with jquery or javascript
<p>Is there a way to check if a function has completed its operation using either javascript or jquery?</p>

<p>I'm trying to make a counter that slows down as the number gets bigger(decelerating the output, if you will), using setTimeout. As you know, the larger the number the longer the delay (in setTimeout). </p>

<p>What I'm trying to do is click a button, then current loop iteration is printed on the screen. This loop number is used as the setTimeout delay, so while the number is low it will quickly rush through, as it gets bigger the delay is larger thus making it print the number more slowly (since this number is the delay and the larger the delay the less often it prints it). </p>

<pre><code>Here is the logic I'm trying to accomplish
1. Click button
2. Initiate loop
3. trigger function to set timeout
4. set timeout triggers a function to print the loop iteration #
5. Repeat step 3 until the number of set iterations is completed
</code></pre>

<p>Well, as you can see when the timeout is set the loop will continue, but there will be a timeout delay. Is there any way that I can put a pause-type function that waits until the timeout function is completed, and then continue onto the next iteration?</p>

<p>Here is my code</p>

<pre><code>&lt;html&gt;
&lt;head&gt;
&lt;script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"&gt;&lt;/script&gt;
&lt;/head&gt;

&lt;body&gt;
&lt;form&gt;
&lt;input type="button" value="Display alert box"
onclick="setMessage()" /&gt;

&lt;script&gt;

 function setMessage(){
 for(i=0;i&lt;5000;i++){
 var b = i;
 timeMsg();
//some sort of puase here checking until timeMsg &amp; docWrite are completed, then continue to the next iteration
    }
}

function timeMsg(){
var t=setTimeout("docWrite()",b);
}   


function docWrite(){
document.write(i);
}
&lt;/script&gt;
&lt;/form&gt;
&lt;/body&gt;
&lt;/html&gt;
</code></pre>
