简体   繁体   中英

How do I add a delay in java script?

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

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();

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM