Search code examples
javascriptfor-loopasynchronousasync-awaitcancellation

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


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)
  }
}


Solution

  • 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.