Duration is passed by value, not by reference. Therefore, animate does not store a link to duration . Even if you update the options object (which is passed by reference), jQuery uses options.duration internally, which means that it will be passed by value.
As a quick fix, you can stop the animation and restart it with a new duration - a setting for part of an already completed animation.
You will need to think about how you want it to behave, for example, when you increase the animation by 4 seconds to a 2-second animation in 3 seconds. In the code below, the animation will be immediate. Thinking about it, maybe this is not what you want, since you probably really care about speed, not duration.
The code below is a rough sketch, I'm not sure how accurate it is if it works when reducing animation values ββor how it handles multiple animation values. You can also change the duration only once.
var state = false, duration = 8000; $(document).click(function (e) { state = true; duration = 1000; }); var animationCss = {top:200, left:200}; $('#foo').animate(animationCss, { duration: duration, step: function(now, fx){ if(state) { $("#foo").stop(); var percentageDone = (fx.now - fx.start) / (fx.end - fx.start) var durationDone = fx.options.duration * percentageDone; var newDuration = duration - durationDone; if (newDuration < 0) { newDuration = 0; } $("#foo").animate(animationCss, { duration: newDuration}) } } });
http://fiddle.jshell.net/5cdwc/3/
source share