1

I am trying to create a visualizer for sorting an array of integers. I need to draw the representation after each iteration of the sort and add a delay so that it does not happen instantly and only show the sorted array. However, the setTimeout does not seem to be working and it is just displaying a representation of the sorted array instead of after each iteration. The code is in java script.

function sort(){
  var len = arr.length;
   for (var i = len-1; i>=0; i--){
    for(var j = 1; j<=i; j++){
       if(arr[j-1]>arr[j]){
           var temp = arr[j-1];
           arr[j-1] = arr[j];
           arr[j] = temp;
           setTimeout(startDraw, 3000);
        }
     }
   }
}
William C
  • 13
  • 2
  • `await` a `Promise` that resolves after the desired number of milliseconds – CertainPerformance Dec 24 '18 at 06:50
  • Possible duplicate of [What is the JavaScript version of sleep()?](https://stackoverflow.com/questions/951021/what-is-the-javascript-version-of-sleep) – holydragon Dec 24 '18 at 06:55
  • 3
    Possible duplicate of [How do I add a delay in a JavaScript loop?](https://stackoverflow.com/questions/3583724/how-do-i-add-a-delay-in-a-javascript-loop) – Herohtar Dec 24 '18 at 06:55
  • this might be helpful for you https://javascript.info/async-await –  Dec 24 '18 at 06:57

2 Answers2

0

You need to understand what you're doing here. If you invoke setTimeout the way you're doing, that doesn't serve the purpose, because the initial loop still completes without waiting for your setTimeout. So, you have to: 1. Break from the loops and 2. Invoke your draw function before breaking

var arr = [5,4,4,6,7,7,21,45,5,7,87,1,3,5,65];

function sort(){
  var len = arr.length;
  loop1:
   for (var i = len-1; i>=0; i--){
   loop2:
    for(var j = 1; j<=i; j++){
       if(arr[j-1]>arr[j]){
           var temp = arr[j-1];
           arr[j-1] = arr[j];
           arr[j] = temp;
           console.log(arr);
           setTimeout(sort, 1000);
           break loop1;
        }
     }
   }
}

sort();
Chiranjib
  • 1,763
  • 2
  • 17
  • 29
0

Try with let instead of var.

function sort(){
   let len = arr.length;
    for (let i = len-1; i>=0; i--){
       for(let j = 1; j<=i; j++){
          if(arr[j-1]>arr[j]){
            let temp = arr[j-1];
            arr[j-1] = arr[j];
            arr[j] = temp;
            setTimeout(startDraw, 3000);
       }
    }
  }
}
Deepak Preman
  • 113
  • 1
  • 11