function sleep(ms) { // new code: checkout a video about promises
return new Promise(resolve => setTimeout(resolve, ms));
}
async function mergeDraw(anArray,startPoint){
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
j = startPoint;
for(num = 0; num < anArray.length; num++){
anArray[num][1] = j;
ctx.lineWidth = 3.2 ;
ctx.strokeStyle = 'seagreen'
ctx.beginPath();
ctx.moveTo(j, 0);
ctx.lineTo(j, 800);
ctx.stroke();
ctx.lineWidth = 3;
ctx.strokeStyle = 'black'
ctx.beginPath();
ctx.moveTo(j, 0);
ctx.lineTo(j, anArray[num][0]);
ctx.stroke();
j+=8;
}
await sleep(10);
}
function merger(arr1, arr2) {
let i = 0,j = 0,mergedArr = [];
while (i < arr1.length && j < arr2.length) {
if (arr1[i][0] > arr2[j][0]){
mergedArr.push(arr2[j]);
j++;
} else{
mergedArr.push(arr1[i]);
i++;
}
}
while (i < arr1.length) {
mergedArr.push(arr1[i]);
i++;
}
while (j < arr2.length) {
mergedArr.push(arr2[j]);
j++;
}
var lowest = mergedArr[0][1];
for( num = 1; num < mergedArr.length; num++){
if(mergedArr[num][1] < lowest){
lowest = mergedArr[num][1];
}
}
mergeDraw(mergedArr, lowest);
return mergedArr;
}
function mergeSort(array) {
//Array of length 1 is sorted so we return the same array back
if (array.length == 1) return array;
//Break down the array to half from middle into left and right
let middle = Math.floor(array.length / 2);
let left = mergeSort(array.slice(0, middle));
let right = mergeSort(array.slice(middle));
//Return the merged sorted array
return merger(left, right);
}
I am trying to make a visualization for mergeSort. My mergeSort function divides my bigger array into smaller arrays. These smaller arrays are then sorted into the mergeArr array by the merger function. The mergeDraw then draws the changes made. I want there to be a small pause after the drawing has been made before the a new mergedArr is drawn. I tried to do this using async await but this doesn't work. Is there a better way to do this instead of using async await?