Skip to content Skip to sidebar Skip to footer

How To Avoid Jimp Blocking The Code Node.js

I'm using Jimp to manipulate some photos. I have an array with photos. Like this: var images = ['.../pic-1.jpg', '.../pic-2.jpg', '.../pic-3.jpg', '.../pic-4.jpg']; And this is th

Solution 1:

It may seem like this because everything happens in parallel instead of in sequence, or maybe indeed the most time is spent in img.quality() and it's a CPU-intensive task that blocks the main thread.

You can try changing this:

images.forEach(function(image){
  jimp.read(image, function(err, img){
    img.quality(90, function(){
      processed++;
      document.querySelector('p').textContent = 'processed images: ' + processed;
    });
  });
});

to something like this:

let processed = 0;
letf = () => {
  jimp.read(images[processed], function(err, img){
    img.quality(90, function(){
      processed++;
      document.querySelector('p').textContent = 'processed images: ' + processed;
      if (processed < images.length) setImmediate(f);
    });
  });
};

You can also change setImmediate to setTimout with some timeout value that would let the UI thread to draw on the screen what it needs to draw. You could even use the window.requestAnimationFrame() for that.

Post a Comment for "How To Avoid Jimp Blocking The Code Node.js"