How to create pause or delay in FOR loop?

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

    var wonderfulFunction = function(i) {
       var s = document.getElementById("div1"); //you could pass this element as a parameter as well
       i = i || 0;
       if(i < 10) {
          s.innerHTML = s.innerHTML + i.toString();
    
          i++;
          //create a pause of 2 seconds.
          setTimeout(function() { wonderfulFunction(i) }, 2000);          
       }
    }
    
    //first call
    wonderfulFunction(); //or wonderfulFunction(0);
    

    You can't pause javascript code, the whole language is made to work with events, the solution I provided let's you execute the function with some delay, but the execution never stops.

提交回复
热议问题