[英]settimeout call function for canvas timer
I wrote this code and I have problem with setTimeout call function for delay 我写了这段代码,我对setTimeout调用函数有延迟的问题
This is a timer but setTimeout doesn't work every second 这是一个计时器,但setTimeout不能每秒工作
Why? 为什么?
<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>
Thanks 谢谢
The code 编码
setTimeout(timer(sec+0.03),1000);
... calls the timer
function and passes its return value into setTimeout
, exactly the way foo(bar())
calls bar and passes its return value into foo
. ... 调用
timer
函数,并将其返回值传递给setTimeout
,就像foo(bar())
调用 bar并将其返回值传递给foo
。 Since your timer
function (implicitly) returns undefined
, and setTimeout
doesn't do anything when you pass it undefined
, that calls timer
(immediately) and then does nothing. 由于您的
timer
函数(隐式)返回undefined
,而setTimeout
在您传递undefined
时不执行任何操作,因此(立即)调用timer
,然后不执行任何操作。
If you want to schedule a call to timer
with sec+0.03
as its argument, create a function that does that: 如果要安排以
sec+0.03
作为其参数的timer
调用,请创建一个执行该操作的函数:
setTimeout(function() {
timer(sec+0.03);
}, 1000);
this line is wrong: setTimeout(timer(sec+0.03),1000); 这行是错误的:setTimeout(timer(sec + 0.03),1000); the first parameter is undefined, not a function.
第一个参数是不确定的,不是函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.