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);
}
}
}
我的setTimeout完整代码FIDDLE
和
我的 setInterval 完整代码 FIDDLE
我做错了什么?
最佳答案
除了 Pointy 的回答之外。由于 js 的单线程架构,您永远不会在 setInterval 中获得 0ms 的步骤,在某些浏览器中,这将接近 0ms,但它永远不会与向下浏览浏览器直到完成的循环相同。
在我的 chrome 中,平均为 5.3 毫秒,在我的 IE10 中,平均为 3.4 毫秒。也许这就是您所说的“setInterval 太慢”的意思。
关于javascript - 为什么javascript setTimeout 延迟不起作用并且 setInterval 太慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18035669/