0

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
  }
  • `setOpacity` in your for loop is called synchronously. You need an async for loop or an array of Promises. Also, `setOp` is undefined. – briosheje Jun 18 '19 at 09:25
  • setOpactiy is async function and when await called next step in loop is running for next element. I need to stop setOpacity from previous run and do next one with new data. setOp - undefined it's just example code - full code is big for stakcoverflow. – Alexander Malyshev Jun 18 '19 at 10:13
  • The issue is that, in the for loop, `setOpacity` **will not work asynchronously**, because the for loop is **not** asynchronous. You need an asynchronous for loop. https://stackoverflow.com/questions/11488014/asynchronous-process-inside-a-javascript-for-loop – briosheje Jun 18 '19 at 10:15
  • You are mistaken. I see parallel running of several async functions. – Alexander Malyshev Jun 18 '19 at 10:46
  • Fix it global sync variable to stop all of async callbacks and addition wait on start of hook function to counter of functions should be zero. Also hook function should be set as async and wait inserted into wait loop on the start. – Alexander Malyshev Jun 19 '19 at 16:11

0 Answers0