Tomek Buszewski Tomek Buszewski - 22 days ago 6
Javascript Question

Element from array being removed too early?

I'm making a simple images lazy loading mechanism. I start with an array of images to process, and when I load each one, I want to remove the said image from array.

My code is as follows:

const removeFromArray = (id) => {
const position = images.indexOf(id);

if (id.classList.contains(classes.loaded)) {
images.splice(id, 1);
}
}

const setHeight = (img, target) => {
const parentWidth = img.parentNode.offsetWidth;
const initw = target.width;
const inith = target.height;

return (parentWidth / initw) * inith;
}

const loadImage = (img) => {
const image = new Image();

img.classList.add(classes.loading);
image.src = img.getAttribute('data-lazy-img');
image.onload = function(e) {
const target = e.target || e.srcElement;

img.style.height = `${setHeight(img, target)}px`;
img.classList.add(classes.loaded);
img.classList.remove(classes.loading);
img.src = img.getAttribute('data-lazy-img');

removeFromArray(img);
}
}


Problem is, sometimes the wrong image gets removed (especially when I remove the latter ones).

My whole code is here: http://codepen.io/tomekbuszewski/pen/LbRQxq?editors=0011

What can I do?

Answer

It seems to make no sense to call splice with an image id as parameter:

 images.splice(id, 1);

You probably meant to do this:

 images.splice(position, 1);