Reputation: 2387
Explanation
I'm trying to change duration of a jQuery animation before it's completed, so I wrote the animation's code inside a function, where the duration is a variable. The animation has queue: false
to start immediately when the duration's variable is changed and the function is called again with a button.
The problem:
When I click on the mentioned button the animation durantion changes, but when it finish it starts again with the previous duration. Here is a fiddle with the code.
var dur;
function foo(){
$('.content').animate({width: '100%'},
{
duration: dur,
easing: 'linear',
queue: false,
done: function(){
$(this).css({width: '0%'});
console.log('Prueba');
}
})
};
$('.start').click(function(){
dur = 5 * 1000;
foo();
});
$('.dur').click(function(){
dur = 0.5 * 1000;
foo();
});
.content {
width: 0%;
height: 20px;
float: left;
margin-top: 20px;
background: #fdcfa2;
border: 1px solid #b18963;
color: #b18963;
}
button {
width: 50%;
cursor: pointer;
padding: 15px 0;
float: left;
background: #d0fac0;
border: 1px solid #6f9b5e;
color: #6f9b5e;
}
button:nth-child(2) {
background: #fff4a8;
border: 1px solid #b1a763;
color: #b1a763;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="start">Start</button>
<button class="dur">Duration to 0.5 s</button>
<div class="content"></div>
Upvotes: 3
Views: 1402
Reputation: 1398
The problem is that after the second animation has finished running, the first animation hasn't yet completed. Simply add a stop() to the previous animation, like this.
function foo(){
$('.content').stop(); // stops the previous animation if running
$('.content').animate({width: '100%'},
{
duration: dur,
easing: 'linear',
queue: false,
done: function(){
$(this).css({width: '0%'});
console.log('Prueba');
}
})
};
Upvotes: 2