0

I'm simply trying to halt execution after every swap made in bubble sort so that I can see the changes, hence how can I make the function halt execution for a few seconds i.e. have a python equivalent of sleep() function in reactjs

bubbleSort(){
        const {array} = this.state;
        for(let i = 0; i < array.length; i++){
            for(let j = 0; j < array.length-i-1; j++){
                if(array[j] > array[j+1]){
                    let temp = array[j];
                    array[j] = array[j+1];
                    array[j+1] = temp;
                    //halt for an interval on n seconds
                }
            }
        }   
    }
Rohan
  • 1
  • 2

1 Answers1

0

You can make a custom sleep function using Promises and setTimeout and use it inside your async/await bubbleSort like so :-

let state = {array:[2,3,1,9,-23,4,5,6]}

async function bubbleSort(){
        const {array} = state;
        for(let i = 0; i < array.length; i++){
            for(let j = 0; j < array.length-i-1; j++){
                if(array[j] > array[j+1]){
                    let temp = array[j];
                    array[j] = array[j+1];
                    array[j+1] = temp;
                    await sleep(1000);
                    console.log('Halted');
                }
            }
               
        }   
      return state.array;
      }

function sleep(duration){
return new Promise((resolve)=>{
 setTimeout(resolve,duration)
})
}
    
bubbleSort();
    
Lakshya Thakur
  • 6,191
  • 1
  • 7
  • 30