How to create pause or delay in FOR loop?

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

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

    if you want to create pause or delay in FOR loop,the only real method is

    while (true) {
        if( new Date()-startTime >= 2000) {
            break;
        }
    }
    

    the startTime is the time before you run the while but this method will cause the browsers become very slow

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

    The following code is an example of pseudo-multithreading that you can do in JS, it's roughly an example of how you can delay each iteration of a loop:

    var counter = 0;
    
    // A single iteration of your loop
    // log the current value of counter as an example
    // then wait before doing the next iteration
    function printCounter() {
        console.log(counter);
        counter++;
        if (counter < 10)
            setTimeout(printCounter, 1000);
    }
    
    // Start the loop    
    printCounter();
    
    0 讨论(0)
  • 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));
    
    }
    
    0 讨论(0)
  • 2021-02-01 20:42

    This is how you should do it

    var i = 0;
    setTimeout(function() {
       s.innerHTML = s.innerHTML + i.toString();
       i++;
    },2000);
    
    0 讨论(0)
  • 2021-02-01 20:43

    It is not possible to pause a loop. However you can delay the execution of code fragments with the setTimeout() function. It would not make a lot of sense to pause the entire execution anyway.

    0 讨论(0)
提交回复
热议问题