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,087
  • 3
  • 15
  • 27

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,542
  • 26
  • 51
  • 1
    Looping in a `while(...)` will peg the CPU while the condition is true. – Greg B Dec 17 '12 at 12:22
  • Thx =), I know, i added it because he asked for something like a sleep function, I were editing the answer to point that out and add more stuff, but this took me a while – Moritz Roessler Dec 17 '12 at 12:39
  • Thanks for the answer and your efforts. I made it work using this "[CODE](http://jsfiddle.net/cynNy/1/)" What I am really interested is in doing this using for loop. Using "Sleep" isn't necessary for me. – rohan_vg Dec 17 '12 at 12:42
  • Why does it has to be a for loop ? – Moritz Roessler Dec 17 '12 at 12:52
  • @Glutamat - This is the reason why I want to do it using FOR LOOP [FIDDLE](http://jsfiddle.net/dYRR2/1/) – rohan_vg Dec 17 '12 at 14:09
  • @user1688606 That doesn't clarify why you need a `for` loop. You should explain your reasons in your question so we're not guessing. – Greg B Dec 17 '12 at 19:30
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
  • 170,779
  • 38
  • 263
  • 309
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,597
  • 18
  • 87
  • 141