In my game I am going to add obstaceles that move left to right across the <div id="outline"></div>
I've used setInterval(){...}
with the .animate()
In it, and it seems to work only issue is after a little bit of time it leaves the ouline, Below is some code and a link.
$(document).ready(function() {
setInterval(function(){
$("#CObject").animate({
'marginLeft' : "+=220px" //moves left
}, 900);
}, 900);
setInterval(function(){
$("#CObject").animate({
'marginLeft' : "-=220px" //moves left
}, 900);
}, 1000);
});
Link.
In my game I am going to add obstaceles that move left to right across the <div id="outline"></div>
I've used setInterval(){...}
with the .animate()
In it, and it seems to work only issue is after a little bit of time it leaves the ouline, Below is some code and a link.
$(document).ready(function() {
setInterval(function(){
$("#CObject").animate({
'marginLeft' : "+=220px" //moves left
}, 900);
}, 900);
setInterval(function(){
$("#CObject").animate({
'marginLeft' : "-=220px" //moves left
}, 900);
}, 1000);
});
Link.
Share Improve this question asked Dec 30, 2014 at 15:52 Nicholas AyoubNicholas Ayoub 891 silver badge7 bronze badges4 Answers
Reset to default 4change to this on your "-=220px":
setInterval(function(){
$("#CObject").animate({
'marginLeft' : "-=220px" //moves left
}, 900);
}, 900);
to match 900 time interval, it's offset by 100.
If you want to know. There's another way do what you want without use setInterval, in this case you have to wait the animation ends in order to start the reverse animation.
$(document).ready(function() {
animate(false);
});
function animate(reverse) {
$("#CObject").animate({
'marginLeft' : (reverse) ? "-=220px" : "+=220px" //moves left
}, 900, function() {
// Run when animation finishes
animate(!reverse);
});
}
This way you can be sure that animation will finish before start anything else
Without setInterval:
$(document).ready(function() {
function loop() {
$("#CObject").animate({
'marginLeft' : "+=220px" //moves left
}, 900, 'linear', function() {
loop();
});
$("#CObject").animate({
'marginLeft' : "-=220px" //moves left
}, 900, 'linear', function() {
loop();
});
}
loop();
});
fiddle
create a loop function with the animation and then just call it when the animation finishes.
To ensure that the animation is plete, I would just have each direction animation call the other one when it pletes. If you look at the API for animate
, you'll see the fourth parameter is for a function that will be called when the animation is finished. http://api.jquery./animate/
$(document).ready(function() {
animateRight();
});
function animateRight() {
$("#CObject").animate({
'marginLeft' : "+=220px" //moves left
}, 900, 'swing', animateLeft);
}
function animateLeft() {
$("#CObject").animate({
'marginLeft' : "-=220px" //moves right
}, 900, 'swing', animateRight);
}
Here is the fiddle: http://jsfiddle/cgdtfxxu/