0

I don't even know how to get started with this: I need a for loop that executes a function (say a simple console.log()) with a timed delay between each execution. I've been trying to do it with setTimeout() and it never works. If I call the function that has the loop from setTimeout, it won't work. Ideally I'd want my for loop to print something x times, with a couple of seconds delay between each printing. Any ideas how that might work? I've tried something like this:

function printStuff(){
for(var i=0;i<5;i++){
console.log(i);
}
};
setTimeout(printStuff(),1000);
3
  • 1
    How about setInterval()? Commented Jun 3, 2015 at 13:21
  • Show what you have tried. This answer has an example Commented Jun 3, 2015 at 13:21
  • setInterval() or delay() if you are using jQuery Commented Jun 3, 2015 at 13:21

8 Answers 8

6

For me you should execute setInterval and inside this you should increase counter. When counter reach the limit you simply clear interval.

var counter = 0;
var limit = 10;
var myVar = setInterval(function(){ 
    if (counter > limit)
    {
        clearInterval(myVar);
    }
    counter++;
    console.log("test"); 
}, 1000);
Sign up to request clarification or add additional context in comments.

Comments

3
init();

function init() {
  setTimeout(init, 2*1000); // wait 2 sec then call init again

  console.log(Date());
}

Or use setInterval:

// Call init after 2 sec and repeat calling it every 2. sec
setInterval(init, 2*1000);

function init() {
  console.log(Date());
}

Comments

1

You could use the async module.

var count = 0;
async.whilst(
    function () { return count < 5; },
    function (callback) {
        count++;
        console.log(count);
        setTimeout(callback, 1000);
    },
    function (err) {
        // 5 seconds have passed
    }
); 

This way the count will be printed every second

Comments

1
var i = 0;
function timeout(){
    setTimeout(log, 1000);
} 
function log(){
    console.log(i++);
    timeout();
}
log();

http://jsfiddle.net/sq4v0kbf/

Comments

0

Use setInterval() instead of setTimeout(). Parameters are just the same:

setInterval(function () {
  // your utility code goes here
}, 2000);

Comments

0

Here is one more way to do it. Use a wrapper function.

var time = 2000;
for (var i = 0; i < 10; i++) {
    (function (i) {
        setTimeout(function () {
            console.log(i);
        }, time);
    })(i);
    time+=2000;

}

Comments

0

You can create a sort of delayed loop function with the number of iterations/times you want to run. Something like this:

var delayedLoop = function (n, milliseconds) {                                       
    var iteration = function (n) {                                              
        if (n > 0) {
            n--;
            console.log(n);                                             
            setTimeout(function () {                                               
                iteration(n)                                                          
            }, milliseconds);                                                              
        }                                                                        
    };                                                                         
    iteration(n);                                                               
}
delayedLoop(4, 1000);

You could even expand the idea and even passing a function to be executed each time.

See demo.

Comments

0

Here's what I think is simpler (and doesn't have the fallbacks of) than a setInterval

    var limit = 10,
      counter = 0,
      delay = 1000;

    function doIt() {
      document.body.innerHTML += 'Hit counter: ' + (counter++) + '<br />';
      if (counter < limit) {
        setTimeout(doIt, delay);
      }
    }
    doIt();

And you can generalize it

function runTimedLoop(delay, howMany, callback) {
  var index = 0;

  function iteration() {
    callback(index++);
    if (index < howMany) {
      setTimeout(iteration, delay);
    }
  }
  iteration();
}

runTimedLoop(1000, 10, function(index) {
  document.body.innerHTML += 'Hit counter: ' + (index++) + '<br />';
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.