I am playing around with a fractal drawing recursive function encountered in Eloquent JavaScript.
I want to set a delay for the drawing of each branch - for the purpose of visualizing the flow of branches/recursive calls as I tinker with this function and its parameters.
The way I have used setTimeout
in the code below does not seem to work, and I am confused as to why.
I expected cx.fillRect(...)
to draw a branch with each delay; rather then stack up in a queue, since there is no other code outside the setTimeout
to wait for.
Below I have included first the working fractal drawing html/js code with no attempt at including a delay. The second snippet of code is my attempt at including a setTimeout
delay.
My non-working attempt at using setTimeout
:
<canvas width="600" height="300"></canvas>
<script>
let cx = document.querySelector("canvas").getContext("2d");
function branch(length, angle, scale) {
setTimeout(() => {
cx.fillRect(0, 0, 1, length);
if (length < 8) return;
cx.save();
cx.translate(0, length);
cx.rotate(-angle);
branch(length * scale, angle, scale);
cx.rotate(2 * angle);
branch(length * scale, angle, scale);
cx.restore();
}, 80);
}
cx.translate(300, 0);
branch(60, 0.5, 0.8);
</script>
Working code without delay:
<canvas width="600" height="300"></canvas>
<script>
let cx = document.querySelector("canvas").getContext("2d");
function branch(length, angle, scale) {
cx.fillRect(0, 0, 1, length);
if (length < 8) return;
cx.save();
cx.translate(0, length);
cx.rotate(-angle);
branch(length * scale, angle, scale);
cx.rotate(2 * angle);
branch(length * scale, angle, scale);
cx.restore();
}
cx.translate(300, 0);
branch(60, 0.5, 0.8);
</script>