gilbertbw
gilbertbw

Reputation: 690

Settimeout is running fast

I have a while loop calling a function every second:

function draw (){
        console.log(then-now)
    };
var i = 0
while(i < 100){
    setTimeout(draw,1000)
    i++;
};

But this is not waiting a second between each call to draw, it is calling it 100 times at once.

Upvotes: 0

Views: 566

Answers (3)

Bergi
Bergi

Reputation: 664206

You seem to want

while(i < 100){
    i++;
    setTimeout(draw, i*1000);
};

Notice that setTimeout schedules a task for the future, but does not wait - it returns immediately, making your code asynchronous.

However, it is not good practise to queue 100 tasks at once. Better:

var i = 0;
function draw (){
    console.log(then-now)
    if (i<100) {
        i++;
        setTimeout(draw, 1000); // maybe adjusted to actual time
    }
};
draw();

Upvotes: 3

zzzzBov
zzzzBov

Reputation: 179046

setTimeout(draw, 1000);

should be:

setTimeout(draw, 1000 * (i + 1));

So that each timeout created is 1s longer.

The i + 1 is so that the first timeout is 1000, rather than 0, as i starts at 0.

Upvotes: 1

McGarnagle
McGarnagle

Reputation: 102733

Try setInterval:

function draw (){
    console.log(then-now)
    i++;
    if (i >= 100) clearInterval(interval);
};
var i = 0
var interval = setInterval(draw, 100);

If you wanted to use setTimeout, you'd have to set the next iteration from inside the draw function itself.

function draw (){
    console.log(then-now)
    i++;
    if (i < 100) setTimeout(draw, 100);
};
var i = 0;
setTimeout(draw, 100);

This is because setTimeout is asynchronous, so your while loop doesn't pause -- it keeps going, launching each instance of draw almost instantaneously.

Upvotes: 4

Related Questions