WDI-SEA / project-4-issues

Open an issue to receive help on project 4 issues
0 stars 0 forks source link

We have a async functions running and need it to stop based on a event outside of the function #54

Open iwaggoner opened 2 years ago

iwaggoner commented 2 years ago

What stack are you using?

(ex: MERN(mongoose + react), DR(django + react), PEN, etc.)

MERN

What's the problem you're trying to solve?

we run a sort and it will run untill it's complete we want to have a way to stop it early

Post any code you think might be relevant (one fenced block per file)


```  async function bubbleSort(array, n, bTest){

    // Iterative Solution
    // let swapped = false
    // let tempArray = array
    // for(let i=0; i<tempArray.length; i++){
    //   swapped = false
    //   for(let j=0; j<tempArray.length-i-1; j++){
    //     if(tempArray[j] > tempArray[j+1]){
    //       let temp = tempArray[j]
    //       tempArray[j] = tempArray[j+1]
    //       tempArray[j+1] = temp
    //       swapped = true
    //     }
    //   }
    //   if(!swapped){break}
    // }

    // Recursive Solution
    // Base case
    if (n===1) return
    // After each pass, the largest element is pushed to the end
    for(let i=0; i<n-1; i++)
        if(array[i] > array[i+1]){
          // swap arr[i] and arr[i+1]
          await sleepThenSwap(array,i,i+1)
          if(bTest){
            setArrayTest([...array])
          } else {
            setArrayHome([...array])
          }
        }

    // Largest element is moved to end, recur for remaining array
    bubbleSort(array, n-1, bTest)
  }

### If you see an error message, post it here. If you don't, what unexpected behavior are you seeing?

### What is your best guess as to the source of the problem?
Have a conditional the exits the function that is changed by a button press 

### What things have you already tried to solve the problem?
A lot of things we want like any advice
TaylorDarneille commented 2 years ago

My first thought is to flip your for loop to a while loop that checks multiple conditions (using AND), one of which is a state that is changed by a key or button press?

timmshinbone commented 2 years ago

Add a piece of state that will make the function run something like if(funcRunningState === true){run the function} and update that piece of state(funcRunningState) to be false when the button is clicked. Give that a try and let me know how it goes

iwaggoner commented 2 years ago

Because it is async and recursive it takes in the states when called and then never looks at them again even if they are changed

iwaggoner commented 2 years ago

Once the function starts running the only way for it to stop is the if(n === 1) we could add a conditional but it ignores state changes

TaylorDarneille commented 2 years ago

well that's a bitch