When some event happened on site (like scroll etc.) event listener function makes a search and run for all found objects async functions to make fade effect per each one. When the event happened second time the system should sync with previous still running async functions per each object to stop them and start new one.
Removing the event listener has the issue with latest state if several events was happened till last async functions enables listener function again.
How I can found and stop previous running functions?
Timer:
function timer(ms) {
return new Promise(res => setTimeout(res, ms));
}
Async function
async function setOpacity(elem, newOp)
{
// Set setOp to previous value
do{
await timer(time);
setOp = setOp + diff;
elem.style.opacity = setOp;
} while(setOp < newOp);
}
Event listener:
function fadeimg()
{
fadeImg = document.getElementsByClassName("picture");
// Calc opacityToSet;
for (var i =0; i<fadeImg.length; i++)
{
var position = (fadeImg[i].offsetTop - scrolled);
setOpacity(fadeImg[i],opacityToSet);
} // for
}