1

I want to write a for loop which prints number 1 to 10 with intervals after every iteration "like this"

How can I achieve it? I tried sleep() setInterval() setTimeout(") and what not but can't seem to find any working solution. And if possible I would like to do this using pure Javascript only.

function abc(){
    for(i=1;i<=10;i++){
        document.write(i+"<br>");
        sleep(1000);
    }
}
rohan_vg
  • 1,017
  • 3
  • 14
  • 26

3 Answers3

3

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

Moritz Roessler
  • 8,238
  • 23
  • 51
2

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);
Ja͢ck
  • 166,373
  • 34
  • 252
  • 304
0

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();
​
Greg B
  • 14,160
  • 18
  • 81
  • 136