[英]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.