Это мой код для симулятора алгоритма сортировки пузырьков. Алгоритм работает и печатает вывод правильно. Но я хочу отложить каждый шаг в течение 2 секунд, а затем отобразить вывод. Это означает, что я хочу отложить каждую итерацию внутреннего цикла для создания пузырьков. Спасибо.Как применить функцию setTimeout для задержки алгоритма bubbleSort?
<!DOCTYPE html>
<html>
<head>
<style>
input[type=text], select {
width: 60px;
padding: 12px 20px;
margin: 8px 0;
display: inline-block;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
}
input[type=button] {
width: 70px;
background-color: #4CAF50;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
border-radius: 4px;
cursor: pointer;
}
input[type=button]:hover {
background-color: #45a049;
}
div {
width:500px;
border-radius: 5px;
background-color: #f2f2f2;
padding: 20px;
margin:0 auto;
}
Canvas{
padding-left: 0;
padding-right: 0;
margin-left: auto;
margin-right: auto;
margin-top:10px;
display: block;
border-radius: 5px;
background-color: #f2f2f2;
}
#pp{
width:300px;
margin-left:3px;
}
#alltext{
height:300px;
width:500px;
}
</style>
</head>
<body>
<h3 align="center"style="text-decoration:underline">Algoritham Simulator</h3>
<div align="center">
<form >
<label >Insert Numbers </label>
<input id="pp" type="text" >
<input type="button" onClick="myMove()" value="Sort" >
</form>
</div>
<canvas id="myCanvas" height="10000" width="900">
Your browser does not support the HTML5 canvas tag.
</canvas>
<script>
var height1 = 10;
var height2 = 50;
var count =0;
var canvas;
var ctx;
function setCanvas(){
canvas = document.getElementById('myCanvas');
ctx = canvas.getContext('2d');
ctx.canvas.height =10000;
ctx.canvas.width = 900;
}
function draw(cars,j){
height1+=85;
height2+=85;
count++;
var rectSize = 80;
var horizontalGap=1;
for(var i=0;i<cars.length;i++) {
if(i==j || i==j+1){
ctx.beginPath();
ctx.fillStyle="green";
ctx.fillRect((rectSize+horizontalGap),height1,rectSize,rectSize);
ctx.closePath();
ctx.fillStyle="white";
}else{
ctx.beginPath();
ctx.fillStyle="black";
ctx.fillRect((rectSize+horizontalGap),height1,rectSize,rectSize);
ctx.closePath();
ctx.fillStyle="white";
}
var text = cars[i];
ctx.fillText(text, (rectSize+40)+horizontalGap ,height2);
horizontalGap+=100;
}
}
function myMove() {
setCanvas();
var yourArray = [];
var inputText = document.getElementById("pp").value;
yourArray=inputText.split(",");
bubbleSort(yourArray);
}
function bubbleSort(items) {
var length = items.length;
for (var i = 0; i < length; i++) { //Number of passes
var c=0;
for (var j = 0; j < (length - i - 1); j++) { //Notice that j < (length - i)
//Compare the adjacent positions
if(items[j] > items[j+1]) {
//Swap the numbers
var tmp = items[j]; //Temporary variable to hold the current number
items[j] = items[j+1]; //Replace current number with adjacent number
items[j+1] = tmp; //Replace adjacent number with current number
}
}
draw(items,j);
}
}
</script>
</body>
</html>
Добро пожаловать в Stack Overflow. Вы можете улучшить свой вопрос. Пожалуйста, прочитайте [Минимальный, Полный и Подтверждаемый пример] (http://stackoverflow.com/help/mcve). Когда ваш код показывает вашу точную проблему ни с чем лишним, вы проявляете уважение к тем, кто добровольно помогает вам. Например, что делает '' CSS'', связанным с вашим вопросом? – zhon
Вы можете просто использовать setTimeout для вызова функции draw – fubbe