I’m trying to pause a function until another function has completed its task. Is there anything similar to .ajaxComplete() but for the completion of a function?
This code should simply print out “test” quickly at first and then slow down (decelerate, if you will). As the number in the loop becomes higher, setTimeout becomes longer, hence, it prints “slower” as the loop goes on. Basically, I need the loop to pause until the function has printed.
edit – I updated my code. “test” is only printed once and nothing else happens.
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
</head>
<body>
<input type="button" value="Display alert box" onclick="docWrite()" />
<script>
var b = 0;
function docWrite() {
document.write("test");
timeMsg();
}
function timeMsg() {
b += 250;
if (b < 5000) { //check the limit
setTimeout("docWrite()", b - 250); //substract 250 (because we already added 250 before the first print
}
}
</script>
</body>
</html>
I think it would be better to let the timeout function start a new timeout function
This would solve your problem and get rid of the for loop altogether. Simply call timeMsg() to start the example.
Modifying your own script I end up with this: