Is it possible to change the duration of a currently running jQuery animation between two different values?
I’ve tried to change the duration via direct assignment, but no success:
var timing = { duration: 4000 };
$(document).click(function (e) {
timing.duration = 1000;
});
$('#foo').animate({top:200, left:200}, timing);
…and even, changing the fx.options.duration in step-method does not affect the running animation:
var state = false,
$(document).click(function (e) {
state = true;
});
$('#foo').animate({top:200, left:200}, {
duration: 4000,
step: function(now, fx){
if(state) fx.options.duration = 1000;
console.log(fx.options.duration); // 1000
}
});
Here’s a fiddle to play around.
Any ideas how this can be done?
The duration is passed by value, not by reference. So
animatedoes not store a reference toduration. Even if you update the options object (which is passed by reference) jQuery usesoptions.durationinternally, which means it will be passed by value.As a quick fix you could stop the animation and restart it with the new duration – adjusting for the part of the animation that is already over.
You’d need to consider how you want it to behave, for example when you speed up a 4 second animation to a 2 second animation after 3 seconds. In the code below the animation will be immediate. Thinking about it, that’s probably not what you want since you probably really care about speed, not duration.
The code below is a rough sketch, I’m not sure if it’s accurate, if it works when decreasing animation values or how it handles multiple animation values. You can also only change the duration once.
http://fiddle.jshell.net/5cdwc/3/