How to create pause or delay in FOR loop?

前端 未结 12 1525
长情又很酷
长情又很酷 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: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.

提交回复
热议问题