[英]setTimeout not causing a 'delay'
I'm tying to use a setTimeout() to cause a delay between circles being drawn on a canvas 我想使用setTimeout()导致在画布上绘制圆之间的延迟
This is the code for the time out 这是超时的代码
setTimeout(drawCircle(myContext, ccX, ccY, cR, circColour, numString), 5000);
This is my drawCircle function 这是我的drawCircle函数
function drawCircle(ctx, x, y, r, colour, drawnNum) {
ctx.beginPath();
ctx.arc(x, y, r, 0, 2 * Math.PI);
ctx.fillStyle = colour;
ctx.fill();
ctx.stroke();
}
When this is run, it isn't waiting 5000ms before executing the function 运行此命令时,它不等待5000ms即可执行该功能
setTimeout
is expecting a reference to a function (or a string of code) that it will call/execute after a delay. setTimeout
期望在延迟后将调用/执行的对函数(或代码字符串)的引用。 You are not passing to it that reference, you are passing the return value of a function call (most likely undefined
). 您没有传递给该引用,而是传递了函数调用的返回值(很可能是
undefined
)。
Your code is exactly the same as: 您的代码与以下代码完全相同:
var returnValue = drawCircle(myContext, ccX, ccY, cR, circColour, numString); // executing the function right away (not waiting for a delay or anything)
setTimeout(returnValue, 5000); // passing the return value of the above call (which is by the way not a reference to a function, nor a string of code) to setTimeout, since it is not a reference to a function setTimeout will omitt it
What you should do is pass a function to setTimeout
like: 您应该做的是将一个函数传递给
setTimeout
例如:
setTimeout(function() { // passing a reference to this anonymous function to setTimeout
drawCircle(myContext, ccX, ccY, cR, circColour, numString);
}, 5000);
or to clear away the confusion: 或消除混乱:
function theFunction() {
drawCircle(myContext, ccX, ccY, cR, circColour, numString);
}
setTimeout(theFuntion, 5000);
// ^^ not a call (no parens here), just passing a reference to theFunction
setTimeout(function(){drawCircle(myContext,ccX,ccY,cR,circColour,numString)},5000);;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.