[英]settimeout call function for canvas timer
我写了这段代码,我对setTimeout调用函数有延迟的问题
这是一个计时器,但setTimeout不能每秒工作
为什么?
<head>
<script>
function timer(sec) {
var c = document.getElementById("arcTimer");
var ctx = c.getContext("2d");
ctx.clearRect(0,0,200,200);
ctx.lineWidth = 20;
ctx.strokeStyle = "#0066CC";
ctx.beginPath();
ctx.arc(100,100,75,-0.5*Math.PI,sec*Math.PI);
ctx.stroke();
if ( sec >= 1.5 ) {
sec = -0.5;
}
setTimeout(timer(sec+0.03),1000);
}
</script>
</head>
<body onLoad="timer(-0.5);">
<canvas width="200" height="200" id="arcTimer" ></canvas>
</body>
谢谢
编码
setTimeout(timer(sec+0.03),1000);
... 调用 timer
函数,并将其返回值传递给setTimeout
,就像foo(bar())
调用 bar并将其返回值传递给foo
。 由于您的timer
函数(隐式)返回undefined
,而setTimeout
在您传递undefined
时不执行任何操作,因此(立即)调用timer
,然后不执行任何操作。
如果要安排以sec+0.03
作为其参数的timer
调用,请创建一个执行该操作的函数:
setTimeout(function() {
timer(sec+0.03);
}, 1000);
这行是错误的:setTimeout(timer(sec + 0.03),1000); 第一个参数是不确定的,不是函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.