简体   繁体   中英

setTimeout not causing a 'delay'

I'm tying to use a setTimeout() to cause a delay between circles being drawn on a canvas

This is the code for the time out

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

This is my drawCircle function

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

setTimeout is expecting a reference to a function (or a string of code) that it will call/execute after a delay. You are not passing to it that reference, you are passing the return value of a function call (most likely 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(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);;

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM