简体   繁体   中英

pause until event/function is completed with jquery or javascript

Is there a way to check if a function has completed its operation using either javascript or jquery?

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).

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).

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

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?

Here is my code

<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
</head>

<body>
<form>
<input type="button" value="Display alert box"
onclick="setMessage()" />

<script>

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

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


function docWrite(){
document.write(i);
}
</script>
</form>
</body>
</html>

Instead of doing this in a for loop, I would recommend doing something like the following:

function docWrite(i){
    document.write(i);
}

function timeMsg(counter) {
  var t;

  counter++;
  if (counter < 5000) {
    t = setTimeout(function(counter){ 
      docWrite(counter);
      timeMsg(counter);
    }, counter, counter)    
  }
}

timeMsg(0);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM