• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

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

almost 3 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

almost 3 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error