Image Pooling for the Win

Dave Taylor
Apr 6, 2016 · 2 min read

Resource throttling

Why not just throttle with no pool?


export class ImagePool {
constructor(poolSize = 10) {
this.available = [];
this.queue = [];
for (let i=0;i<poolSize;i+=1) {
this.available.push(new Image());
}
}

available:HTMLImageElement[];
queue:((img:HTMLImageElement) => void)[];

pop(callback:(img:HTMLImageElement) => void):void {
this.queue.push(callback);
this.next();
}

push(img:HTMLImageElement):void {
if (!img) return;
img.src = '';
this.available.push(img);
this.next();
}

remove():void {
this.available = null;
this.queue = null;
}

private next():void {
if (this.available.length && this.queue.length) {
let callback = this.queue.shift();
callback(this.available.pop());
this.next();
}
}
}
// We create a new instance
const imagePool = new ImagePool();
// Request an image
imagePool.pop((img) => {
// Load the image
img.addEventListener('load', loaded);
img.src = 'mysrc.jpg';
function loaded():void {
// do some work then release the image
img.removeEventListener('load', loaded);
imagePool.push(img);
}
});


Dave Taylor

Written by

Technical Lead, Consultant and Mentor for growing digital teams. Tech Lead at @SecclTech. Organiser at @BathJS.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade