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);
    }
}
5
  • so you want to avoid using setInterval()? Commented Dec 17, 2012 at 12:03
  • What did you try using setTimeout and setInterval? Can we see your code? Commented Dec 17, 2012 at 12:03
  • Possible duplicate stackoverflow.com/questions/951021/… Commented Dec 17, 2012 at 12:03
  • setInterval is actually the function you need, here. Just keep track of a counter, and unset the interval when you've ran it X times. Commented Dec 17, 2012 at 12:04
  • @Matthew Gilliard: I got it working using this code. I was just curious to know how could I do it using FOR LOOP Commented Dec 17, 2012 at 12:38

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

6 Comments

Looping in a while(...) will peg the CPU while the condition is true.
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
Thanks for the answer and your efforts. I made it work using this "CODE" What I am really interested is in doing this using for loop. Using "Sleep" isn't necessary for me.
Why does it has to be a for loop ?
@Glutamat - This is the reason why I want to do it using FOR LOOP FIDDLE
|
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);

Comments

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();
​

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.