What is the best way to throttle a ton of image onload functions? Code example:

while( images.length <= 500 ){
    img.onload = function() {
        drawImage(image,0,0,500,500);
    }
}

I'm trying to prevent all of the drawing happening at once when these 500 images come back at around the same time. I've tried wrapping the onload in setTimeout but I dont want to throttle the downloading of the images, just when they are drawn. Thanks.

有帮助吗?

解决方案

Like most things in javascript canvas drawImage method is synchronous. It means it won't execute the code any furhter until it gets its job done. Your images are indeed loaded one by one but it is so fast you can't see it.

To add a delay to the images loading we can make some kind of a queue. We'll add the images to the array and execute a drawing function after some amount of time:

img.onload = function() {
    images.push(img);
};
(...)

var i = 0;
var images = [];
var timeoutFn;

(function draw() {
    if (images.length) {
        drawImage(images[0],0,0,500,500);
        images.shift();
    }
    timeoutFn = setTimeout(draw, 1000);
})();

Now you'll need to set timeoutFn = null once all the images are loaded. I hope you get the idea.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top