Binding a function to self
You can bind a function to its own reference and then call it directly from the setTimeout
function.
First bind the draw function in the Circle constructor.
function Circle(settings){
Object.assign(this,settings);
this.draw = Circle.prototype.draw.bind(this);
}
Construct the prototype as normal
Circle.prototype = {
draw(){
ctx.beginPath();
ctx.arc(this.x, this.y, this.r, 0, Math.PI * 2);
ctx.stroke();
}
}
Then to draw the circles at intervals you can pass the bound draw function directly to the setTimeout
function.
const circleInterval = 100;
function drawCircles(){
circles.forEach((circle, i) => setTimeout(circle.draw, (i + 1) * circleInterval));
}
Example
//==========================================================
// helper functions randI for random integer and setOf creates an array
const randI = (min, max = min + (min = 0)) => (Math.random() * (max - min) + min) | 0;
const setOf = (count, cb = (i)=>i) => {var a = [],i = 0; while (i < count) { a.push(cb(i ++)) } return a };
//==========================================================
// get canvas an set example constants
const w = canvas.width = innerWidth;
const h = canvas.height = innerHeight;
const ctx = canvas.getContext("2d");
const circleCount = 1500;
const circleInterval = 100;
//==========================================================
function Circle(settings) {
Object.assign(this, settings);
this.draw = Circle.prototype.draw.bind(this);
}
Circle.prototype = {
draw() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.r, 0, Math.PI * 2);
ctx.stroke();
}
}
//==========================================================
// create circle array
const circles = setOf(circleCount, () => new Circle({ x: randI(w), y: randI(h), r: randI(20, 100)}));
//==========================================================
// draw the circles at intervals
function drawCircles() {
circles.forEach((circle, i) => setTimeout(circle.draw, (i + 1) * circleInterval));
}
drawCircles()
canvas {
position: absolute;
top: 0px;
left: 0px;
}
<canvas id="canvas"></canvas>