How to create pause or delay in FOR loop?

前端 未结 12 1521
长情又很酷
长情又很酷 2021-02-01 19:57

I am working on a website, where I need to create a pause or delay.
So please tell me How to create pause or delay in for loop in javascript or

相关标签:
12条回答
  • 2021-02-01 20:20

    I used a do...while loop to put a delay in my code for a modal dialog that was closing too quickly.

    your stuff....
    
    var tNow = Date.now();
    var dateDiff = 0;
    do {
        dateDiff = Date.now() - tNow;
    } while (dateDiff < 1000); //milliseconds - 2000 = 2 seconds
    
    your stuff....
    
    0 讨论(0)
  • 2021-02-01 20:23

    I am executing a function where I need access to the outside object properties. So, the closure in Guffa solution doesn't work for me. I found a variation of nicosantangelo solution by simply wrapping the setTimeout in an if statement so it doesn't run forever.

        var i = 0;
        function test(){
    
            rootObj.arrayOfObj[i].someFunction();
            i++;
            if( i < rootObj.arrayOfObj.length ){
                setTimeout(test, 50 ); //50ms delay
            }
    
        }
        test();
    
    0 讨论(0)
  • 2021-02-01 20:28

    While several of the other answers would work, I find the code to be less elegant. The Frame.js library was designed to solve this problem exactly. Using Frame you could do it like this:

    var s = document.getElementById("div1");
    for (i = 0; i < 10; i++) {
       Frame(2000, function(callback){ // each iteration would pause by 2 secs
          s.innerHTML = s.innerHTML + i.toString();
          callback();
       }); 
    }
    Frame.start();
    

    In this case, it is nearly the same as the examples that use setTimeout, but Frame offers a lot of advantages, especially if the you are trying to do multiple or nested timeouts, or have a larger JS application that the timeouts need to work within.

    0 讨论(0)
  • 2021-02-01 20:29

    I tried all one, but I think this code is better one, it is very simple code.

    var s = document.getElementById("div1");
    var i = 0;
    setInterval(function () {s.innerHTML = s.innerHTML + i.toString();  i++;}, 2000);
    
    0 讨论(0)
  • 2021-02-01 20:29

    It is impossible to directly pause a Javascript function within a for loop then later resume at that point.

    0 讨论(0)
  • 2021-02-01 20:31

    The way I found was to simply use setInterval() to loop instead. Here's my code example :

    var i = 0;
    var inte = setInterval(() => {
        doSomething();
    
        if (i == 9) clearInterval(inte);
        i++;
    }, 1000);
    
    function doSomething() {
        console.log(i);
    };
    

    This loops from 0 to 9 waiting 1 second in between each iteration.

    Output :

    0 1 2 3 4 5 6 7 8 9
    
    0 讨论(0)
提交回复
热议问题