I agree with some comments. There are many good JavaScript libraries that not only make writing code easier, but also eliminate some browser compatibility issues from your hands.
Having said that, you can change your fade functions to accept a callback:
function fadeIn(callback) { return function() { function step() {
So fadeIn will return a function. This function will be used as an onclick handler. You can pass fadeIn function that will be called after you have completed the last step of your animation. The internal function (returned by fadeIn ) will still have access to callback , as JavaScript creates closure around it.
Your animation code may still use many enhancements, but this is briefly what most JavaScript libraries do:
- Perform the animation step by step;
- Check if you are completed;
- Call the user callback after the last step.
One last thing to keep in mind: animation can become quite complex. If, for example, you need a reliable way to determine the duration of an animation, you will want to use the tween functions (also something that most libraries do). If math isnβt your forte, it might not be so nice ...
In response to your comment: you say you want it to continue to work the same way; "If the bussy function, nothing will happen."
So, if I understand correctly, you want the animations to block. In fact, I can tell you two things:
- Your animations are not blocked (at least not the animations themselves - read below).
- You can still work the way you want with any asynchronous animation.
This is what you use done_or_not for. This, in fact, is the big picture. Usually, a boolean value ( true or false ) is used instead of a string, but the principle is always the same:
// Before anything else: var done = false; // Define a callback: function myCallback() { done = true; // Do something else } // Perform the asynchronous action (eg animations): done = false; doSomething(myCallback);
I created a simple animation example that you want to execute using jQuery only. You can look here: http://jsfiddle.net/PPvG/k73hU/
var buttonFadeIn = $('#fade_in'); var buttonFadeOut = $('#fade_out'); var fadingDiv = $('#fading_div'); var done = true; buttonFadeIn.click(function() { if (done) {
Because of the done variable, the buttons will only react if the animation is complete. And, as you can see, the code is really short and readable. This is an advantage of using a library such as jQuery. But, of course, you can create your own solution yourself.
Regarding performance: most JS libraries use tweens to perform animations that are usually more efficient than fixed steps. It definitely looks smoother for the user, because the position depends on the elapsed time , and not on the number of steps taken .
Hope this helps. :-)