I wrote this code and I have problem with setTimeout call function for delay
This is a timer but setTimeout doesn't work every second
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
. 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.
If you want to schedule a call to timer
with sec+0.03
as its argument, create a function that does that:
setTimeout(function() {
timer(sec+0.03);
}, 1000);
this line is wrong: setTimeout(timer(sec+0.03),1000); the first parameter is undefined, not a function.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.