How to create pause or delay in FOR loop?

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

    You can't use a delay in the function, because then the change that you do to the element would not show up until you exit the function.

    Use the setTimeout to run pieces of code at a later time:

    var s = document.getElementById("div1");
    for (i = 0; i < 10; i++) {
    
      // create a closure to preserve the value of "i"
      (function(i){
    
        window.setTimeout(function(){
          s.innerHTML = s.innerHTML + i.toString();
        }, i * 2000);
    
      }(i));
    
    }
    

提交回复
热议问题