gsubiran
gsubiran

Reputation: 2452

Why javascript setTimeout delay is not working and setInterval is too slow

    function paint(ctx, canvas) {
    var veces = 0;
    var interval = 1000;
    dibujo();
    function dibujo() {
        var lado1 = Math.floor((Math.random() * 300) + 1);
        var lado2 = Math.floor((Math.random() * 300) + 1);
        ctx.strokeStyle = '#' + Math.floor(Math.random() * 16777215).toString(16);
        ctx.strokeRect((canvas.width / 2) - (lado1 / 2),
            (canvas.height / 2) - (lado2 / 2),
            lado1,
            lado2);
        veces++;
        if (veces < 1000) {
            setTimeout(dibujo(), interval);
        }
    }
}

My complete code for setTimeout FIDDLE

and

My complete code for setInterval FIDDLE

What i'm doing wrong?

Upvotes: 2

Views: 1538

Answers (2)

Marcel Gwerder
Marcel Gwerder

Reputation: 8520

Just in addition to Pointy's answer. Because of the single threaded architecture of js, you will never get 0ms steps in a setInterval, in some browsers this will get close to 0 ms but it will never be the same as a loop which looks down the browser until its finished.

In my chrome it is an average of 5.3ms and in my IE10 an average of 3.4ms. Maybe that is what you meant with "setInterval is too slow".

Upvotes: 2

Pointy
Pointy

Reputation: 413717

You're calling setTimeout improperly:

    setTimeout(dibujo, interval); // no ()

You have to pass a reference to your function, which is accomplished by using the name of the function. You don't want () because that causes the function to be called before the call to setTimeout happens, with the return value of your function passed in instead of a reference to the function.

Upvotes: 1

Related Questions