First of all, I looked at all the "sleeping" questions lying around (for example, What is the version of JavaScript for sleeping ()? ) But I did not find an acceptable solution.
I would like to make a visual education tool for all kinds of algorithms. For this, I use javascript with jQuery to display data and paint beautifully. To run it, I want to make a sort pattern where the array is displayed, shuffled, and then sorted in a visually pleasing way. So I want the two cells to be highlighted (easy), maybe changed (easy), and then there was a slight delay before the next pair is tested.
I understand that in javascript there is no explicit "sleep" method. However, to restructure the code to use setTimeout, it would imply a recursive rewrite of all my algorithms, which is a huge obstacle (although, obviously, not impossible).
As an example of a problem, consider a sample of sorting bubbles:
function bubble_sort(arr){
for(var i=0;i<arr.length;i++){
for(var j=1;j<arr.length;j++){
highlight(j-1);
highlight(j);
if(arr[j-1] > arr[j]){
visible_swap(arr, j, j-1);
}
sleep(1000);
}
}
exhibit_array(arr);
}
This can obviously be rewritten recursively to work with setTimeout, but it will take a lot of time for all the algorithms that I mean. Am I missing something? Is there a “simple” way to leave implementations as they are and put asleep on their own?
EDIT:
: .
firefox, , ( : https://developer.mozilla.org/en/New_in_JavaScript_1.7). , :
function bubble_sort(arr){
for(var i=0;i<arr.length;i++){
for(var j=1;j<arr.length;j++){
highlight(j-1);
highlight(j);
if(arr[j-1] > arr[j]){
visible_swap(arr, j, j-1);
}
yield true;
}
}
yield false;
}
var bubble = bubble_sort(arr)
function gen(){
if(bubble.next()){
setTimeout(gen, 500);
}
else{
alert("Done!");
}
}
, , firefox. , < script type = "text/javascript; version = 1.7" > . , , . , , .
, :
function bubble_sort(arr){
var q = new Array();
for(var i=0;i<arr.length;i++){
for(var j=1;j<arr.length;j++){
q[q.length] = [ [highlight, j-1 ], [highlight, j] ];
if(arr[j-1] > arr[j]){
swap(arr, j, j-1);
q[q.length] = [ [visible_swap, j, j-1] ];
}
}
}
return q;
}
function play(q, step){
if(q.length == 0)
return;
clear_highlights();
cmds = q.shift();
for(ind in cmds){
cmd = cmds[ind];
f = cmd.shift();
f.apply(null, cmd);
}
setTimeout(function(){ play(q, step); }, step);
}
. , .
, , javascript, , , , , .
!