I’m trying to figure out how to make an animation for an algorithm in JavaScript. More general though, how are algorithm animations done in other languages (i.e. Java)? Is the animation aspect separate from the algorithm logic? So, for example, I have my sorting algorithm working, and I would have a special Animation object that just “observes” the state of the list in question for any changes, or are the snippets in the algorithm logic that notifies the animation object of modifications to the list, and invokes the necessary animation methods?
Back to JavaScript, in may case, I have implemented an Huffman encoding algorithm that works; the only thing I’m trying to do is make an accompanying animation to demonstrate what its actually doing. So far, my approach is to use the d3 library or jquery for the animations, the only thing I’m stuck on is how to actually invoke any animation routines from my algorithm code.
I realize that its not really possible in JavaScript to pause execution at a line of code (or wait) for an animation to complete.
Any suggestions on the best way to approach this problem?
EDIT:
For example, the below code builds a queue of elements, and I would like to animate the queue being built as its doing it:
var i,j;
var input = $('#input').val();
var input_array = input.split('');
for (i=0; i<input_array.length; i++){
var temp = new Node(input_array[i], 1);
for (j=i+1; j<input_array.length; j++) {
if (input_array[j] == input_array[i]) {
temp.frequency++;
input_array.splice(j, 1);
}
}
Queue.push(temp);
}
Yes, that’s true, since animations in JS are asynchronous. You have 2 choices:
Option #1 is more elegant, but of course more complicated – all loops will need to become recursive functions etc. Yet this is the only possibility if your algorithm is non-terminating, or the animation queue of option #2 would become too long (and memory-eating).