Home > Enterprise >  How to stop async for loop that is already in call stack?
How to stop async for loop that is already in call stack?

Time:11-09

When user hits search button first time it works like it should and it takes approx 30sec to fetch all the data, so if the user decides to click the search button again with new search term it all gets messed up because the previous async loop is not done yet. Please help to find a solution to kill previous call stack and restart the process without continuing previous loop.

searchButton.addEventListener("click", (e) => {
e.preventDefault();
getPrice(data);
}

async function getPrice(data) {
  for (singleResult of data) {
      await fetchWeb(Title)
  }
}
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Use a global click counter:

let calls = 0;
searchButton.addEventListener("click", (e) => {
  e.preventDefault();
  getPrice(data,   calls);
}

async function getPrice(data, id) {
  for (singleResult of data) {
    if (id !== calls) break;
//  ^^^^^^^^^^^^^^^^^^^^^^^^
    await fetchWeb(Title)
  }
}

As soon as calls changes, the currently active loop will stop.

  • Related