Reputation: 5628
//this code animates the divs to the left after every 5 secs
$(document).ready(function() {
var refreshId = setInterval(function() {
$('.box').each(function() {
if ($(this).offset().left < 0) {
$(this).css("left", "150%");
} else if ($(this).offset().left > $('#container').width()) {
$(this).animate({
left: '50%'
}, 500);
} else {
$(this).animate({
left: '-150%'
}, 500);
}
});
}, 5000);)
};
In the above code, whenever the page gets loaded the div
elements keep sliding every 5 secs. But there is a button in my webpage which, when clicked, moves the div
elements to the left or right respectively according to the button clicked. But the problem is the auto animation and animation occuring on buuton click sometimes overlap. So whenever I click the button I want to delay the auto animation in document.ready
by 5 secs again.
This is shown in this jsFiddle. When you keep clicking on the "left animation" or "right animation" buttons, the divs overlap sometimes. So I just want to delay the auto animation whenever I click the buttons.
Upvotes: 1
Views: 945
Reputation: 8511
You can call clearInterval(refreshId)
, and then re-run your code to set up the rotation.
Here's a rough sketch of how you could do it. I'm afraid I probably can't provide more detail than this, but I hope it helps!
$(document).ready(function () {
var refreshId;
function startRotation() {
refreshId = setInterval(function () { /* rotate stuff */ }, 5000);
}
function restartRotation() {
clearInterval(refreshId);
startRotation();
}
startRotation();
var button = /* find the buttons that should restart the rotation */;
button.click(restartRotation);
};
Upvotes: 6