简体   繁体   English

为什么JavaScript setTimeout延迟不起作用并且setInterval太慢

[英]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 我完整的setTimeout FIDDLE代码

and

My complete code for setInterval FIDDLE 我完整的setInterval FIDDLE代码

What i'm doing wrong? 我做错了什么?

Just in addition to Pointy's answer. 除了Pointy的答案。 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. 由于js的单线程体系结构,您将永远不会在setInterval中获得0ms的步长,在某些浏览器中,这将接近0 ms,但它永远不会像循环那样向下看浏览器直至完成。

In my chrome it is an average of 5.3ms and in my IE10 an average of 3.4ms . 在我的Chrome中,平均时间为5.3ms ,在IE10中,平均时间为3.4ms Maybe that is what you meant with " setInterval is too slow ". 也许这就是“ setInterval太慢 ”的意思。

You're calling setTimeout improperly: 您不正确地调用了setTimeout

    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. 您不想要()因为这会导致在调用setTimeout 之前调用该函数,并传递函数的返回值而不是对该函数的引用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM