const data=[["https://dummyimage.com/100x100/ad40ad/000000","https://dummyimage.com/100x100/454545/000000","https://dummyimage.com/100x100/789acc/000000","https://dummyimage.com/100x100/994563/000000","https://dummyimage.com/100x100/fff456/000000"],["https://dummyimage.com/100x100/ad40ad/000000","https://dummyimage.com/100x100/454545/000000","https://dummyimage.com/100x100/789acc/000000","https://dummyimage.com/100x100/994563/000000","https://dummyimage.com/100x100/fff456/000000"]];
function loadImageSet(arr) {
return new Promise(res => {
const set = arr.map(src => {
const img = new Image();
img.src = src;
return img;
});
res(set);
});
}
function preload(data) {
return Promise.all(data.map(loadImageSet));
}
async function main(data) {
const images = await preload(data);
const containers = document.querySelectorAll('div');
containers.forEach(c => {
const { id } = c.dataset;
const imageSet = images[id - 1];
c.addEventListener('click', handleClick(c, id, imageSet), false);
});
};
main(data);
function handleClick(container, id, imageSet) {
let index = 0;
container.appendChild(imageSet[index]);
++index;
return function () {
if (index === imageSet.length) index = 0;
const img = container.querySelector('img');
img.replaceWith(imageSet[index]);
++index;
}
}