-
var j = 0;
function bubbleSort() {Timer = setInterval(function() { if (data.length - 1 < 1) { clearInterval(Timer); }; if (data[j] > data[j + 1]) { var swap = data[j]; data[j] = data[j + 1]; data[j + 1] = swap; console.log(j); show(); }; if (j == data.length-2) { j = 0; } else { j++; }; }, 2);
}
-
var j = 0;
function bubbleSort() {
Timer = setTimeout(function() { if (data.length - 1 < 1) { clearTimeout(Timer); }; if (data[j] > data[j + 1]) { var swap = data[j]; data[j] = data[j + 1]; data[j + 1] = swap; console.log(j); show(); }; if (j == data.length-2) { j = 0; } else { j++; }; bubbleSort() }, 2);
}
if (data.length - 1 < 1) {
clearInterval(Timer);
};
如果data.length<=1,interval定时器将被清除,定时器回调函数没有机会被再次执行
if (data.length - 1 < 1) {
clearTimeout(Timer);
};
如果data.length<=1,timeout定时器也被清除,但是回调函数最后又调用了bubbleSort()
,又会设置新的timeout定时器,重复又重复~~~
间隔2ms?
该不会是没反应过来就排完了吧
你执行bubbleSort()了吗