Add a pause/interval to every iteration in a FOR LOOP

回眸只為那壹抹淺笑 提交于 2019-12-07 02:35:28

To answer the question, to get something like a sleep function you could just write somehting like this as a helper function

function sleep(dur) {
 var d = new Date().getTime() + dur;
  while(new Date().getTime() <= d ) {
    //Do nothing
  }

}

console.log(new Date().getTime())
     sleep(1000)

 console.log(new Date().getTime())

Then you could call the sleep function after every iteration like

function abc(){
    for(i=1;i<=10;i++){
        document.write(i+"<br>");
        sleep(1000);
    }
}

But Note that sleep will freeze your browser in this time and you don't really wan't this kind of behaviour when you just want to periodiccally do sth

window.setInterval would be what you want in such cases

    function abcd(i){
       document.write(i + "<br>")
    }


function repeatedTimeout(func,times,duration) {
    var args = Array.prototype.slice.call(arguments).splice(3);
    var i = 0;
    args.push(i)
    var wrap = function () {
     if(args[args.length - 1] >= times)
       window.clearInterval(wrap)
      else {

         func.apply(this,args)
         args[args.length - 1]++
       }
    }
    window.setInterval(wrap,duration)
}
repeatedTimeout(abcd,10,1000)

Which would call it 10 times every 1000 milliseconds, whithout freezing the Browers

Heres the JSBin

Update

If it really has to be a for loop, you could do something like this, regardless of the sense it makes to me

for (var i = 0; i <= 10 ; i++) {
  window.setTimeout(
    (function (i){ 
      return function() {
        document.write(i + "<br>")
      }
    })(i),i * 1000)
  }

In this case heres another JSBin

This would call window.setTimeout in a for loop and a multiple of the timeout with i as the timeout, this would work, but i'd rather suggest using setInterval like you already did in the Fiddle you posted in the comment

Due to the mostly asynchronous (and single threaded) nature of JavaScript in the browser, constructs such as sleep() aren't the way to go.

You can write a generic function using setTimeout() that will do the looping and then pass in the function that should be run at every interval of x milliseconds. At least you'd have a reusable container in which you can run your code.

function loopn(n, fn, delay)
{
    if (n > 0) {
        fn();
        if (n > 1) {
            setTimeout(function() {
                loopn(n - 1, fn, delay);
            }, delay);
        }
    }
}

loopn(10, function() {
    console.log('hello there');
}, 1000);

You could deconstruct the loop into a recursive function and use setTimeout to implement the pause.

var i = 0;
var limit = 10;

function loop(){
    console.log(i);
    i++;
    if(i < limit)
    {

        setTimeout(loop, 100);
    }
}
loop();
​
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!