setTimeout没有导致'延迟'

时间:2017-10-22 23:11:29

标签: javascript

我想使用setTimeout()导致在画布上绘制圆圈之间出现延迟

这是超时的代码

setTimeout(drawCircle(myContext, ccX, ccY, cR, circColour, numString), 5000);

这是我的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();


}

运行此命令时,在执行函数

之前不会等待5000ms

2 个答案:

答案 0 :(得分:3)

setTimeout期望引用一个函数(或一串代码),它将在延迟后调用/执行。你没有传递给那个引用,你传递函数调用的返回值(很可能是undefined)。

您的代码与以下内容完全相同:

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

你应该做的是将一个函数传递给setTimeout,如:

setTimeout(function() {                            // passing a reference to this anonymous function to setTimeout
    drawCircle(myContext, ccX, ccY, cR, circColour, numString);
}, 5000);

或清除混乱:

function theFunction() {
    drawCircle(myContext, ccX, ccY, cR, circColour, numString);
}

setTimeout(theFuntion, 5000);
//                  ^^ not a call (no parens here), just passing a reference to theFunction

答案 1 :(得分:1)

setTimeout(function(){drawCircle(myContext,ccX,ccY,cR,circColour,numString)},5000);