Pausing JavaScript execution for animation of code
I'm having an interesting but difficult problem with my JavaScript code. Basically, I'm trying to create an animation of a simple algorithm using JavaScript (a sorting algorithm, if you're wondering) for educational reasons. I've already got all of the animation code written (using RaphaelJS), and it all works fine. The trouble is getting the animations of the algorithm to happen at the right time. JavaScript doesn't really have any way to "pause" execution, so I can't really step through the algorithm slowly, playing animations at each step. It's obviously much more valuable from an educational perspective if the algorithm proceeds at a pace the student can comprehend.
There are two ways to solve this problem that I can think of, and both suck. The first is to use some crazy setTimeout() code. This would probably be very difficult -- lots of strange code transformations would be needed to associate the different parts of the algorithm with correct timeouts. I've already tried to do this a little bit, and it gets very complicated for a non-trivial algorithm.
The second is to busy-wait. This would probably also work. The problem is that busy waiting is a pretty bad idea in JavaScript code -- I actually crashed Firefox when I wa开发者_如何转开发s testing out this alternative. Basically, I'm wondering if there's another solution here that I'm overlooking. Bonus points if the solution is client-side only, since the amount of freedom I have to serve stuff other than static html and javascript on the school server is questionable.
It's obviously much more valuable from an educational perspective if the algorithm proceeds at a pace the student can comprehend.
What about using links/buttons e.g. < > to allow the user to step through the code by clicking prev/next?
Maybe the only viable workaround and may make more sense for the end user.
Maybe this is too simple to do what you want it to do, but what if you put the segment of code that you want to run between stops into a function, and call that function with the push/click of a button on the page: onclick="runAnimationPiece()"
Your code would need to hold some state to know where it left off from the last time the function ran.
And if you need to run different functions for different pieces of the animation, say, for instance, the first piece should be generated by foo1() and second piece by foo2(), you can create a counter and a function which calls the appropriate animation function (foo1() or foo2(), etc.) based on the counter.
精彩评论