Interval doesn't clear immediately after repeating for a while - javascript

I have a bouncing arrow on my website that I created with Jquery and setInterval, like this:
bouncing = setInterval(function() {
$("div").animate({
top:"30px"
},100,"easeInCubic",function() {
$("div").animate({
top:"0px"
},100,"easeOutCubic");
});
console.log("bounced");
},200);
You can see this in place in a codepen here: http://codepen.io/mcheah/pen/wMmowr
I made it run faster than i needed because its easier to see the issues quicker. My issue is that after leaving the interval running for a few seconds, you'll notice that instead of bouncing back up or down immediately, the bouncing element will stop for half a second and then just hang there, before beginning again. If you leave it running even longer (20 seconds) and then clear the interval, you'll notice that it takes a few seconds to stop bouncing.
My questions are these:
Why does the bouncing go out of sync occasionally?
Why does the clear interval take a while to clear if it's been repeating for a while?
Is there a better way to have a bouncing arrow? Are CSS transitions more reliable?
Thanks for your help!

Your are trying to perfectly coordinate a setInterval() timer and two jQuery animations such that the two come out perfectly coordinated. This is asking for trouble and the two may drift apart over time so it is considered a poor design pattern.
If, instead, you just use the completion of the second animation to restart the first and make your repeat like that, then you have perfect coordination every time.
You can see that here in another version of your codepen: http://codepen.io/anon/pen/NxYeyd
function run() {
var self = $("div");
if (self.data("stop")) return;
self.animate({top:"30px"},100, "easeInCubic")
.animate({top:"0px"}, 100, "easeOutCubic", run);
}
run();
$("div").click(function() {
// toggle animation
var self = $(this);
// invert setting to start/stop
self.data("stop", !self.data("stop"));
run();
console.log("toggled bouncing");
});

It's not a good idea to mix animate() with timers this way. There's NO chance you can synchronize something like this. And there's no need to. You can simply append a function into the animation queue, look here: https://stackoverflow.com/a/11764283/3227403
What animate() does is put an animation request into a job queue which will be processed later, when the right time comes. When you break the interval the stuff that accumulated in the queue will still be processed. There's a method to clear the queue and stop all animation immediately.
The JQuery animation functions actually manipulate CSS, and there is nothing beyond it in HTML. Another option would be using a canvas, but it is a completely different approach and I wouldn't recommend it. With JQuery's animation your already at the best choice.
This is a simple solution to your problem:
function bounce()
{
$("div")
.animate({
top: "30px"
}, 100, "easeInCubic")
.animate({
top: "0px"
}, 100, "easeOutCubic", bounce); // this loops the animation
}
Start bouncing on page load with:
$(bounce);
Stop bouncing on click with:
$("div").click(function() {
$("div").stop().clearQueue().css({ top: "0px" });
// you want to reset the style because it can stop midway
});
EDIT: there were some inaccuracies I corrected now. The running example is on codepen now.

If you want to use javascript for animation you can use something better like the greensock tween library
http://greensock.com/docs/#/HTML5/GSAP/TweenMax/to/
something like this:
var tween = TweenMax.to($("div"), 100, {y: "100px", yoyo: true, repeat: -1});

You could wrap your interval code with:
if(!$("div").is(":animated"))
This will initiate your animation only if your previous one is finished.
The reason why it was bouncing weird is that your animations are queued.
You can check how it works now:
http://codepen.io/luminaxster/pen/XKzLBg
I would recommend using the complete callback when the second animation ends instead and have variable to control a bounce recursive call in this version:
http://codepen.io/luminaxster/pen/qNVzLY

Related

Javascript loop - hide animated div

I'm going to try to make this as descriptive as possible, my apologies in advance if I have difficulties explaining what it is exactly that I am trying to do.
Written Description:
So I am creating a web based game in javascript. This game is a 2 player shooter game. So far, when a player 'shoots' another player, it spawns an animated div which goes from its start (at the gun of player1) to the end of the screen where it then gets removed (using removeChild from the div it was spawned in.)
The problem is that when the bullet 'hits' the player, it jsut keeps on going until the end of the screen. My code does register whether or not the bullet hits the player, but when it does hit the player, I would like it to dissappear either on the player or right after it passes the player, so that it has the effect that it penetrates the player instead of just passing over the player.
Now let me be more specific.
$("#bullet").animate({
marginLeft: '100%'
}, 1000, function(){
document.getElementById("thegame").removeChild("#bullet");
});
basically this is the code that spawns the 'bullet'
now lets say that I wanted to get the bullet to disappear after it's margin passed 70% by doing some sort of loop that checks its position as the animated div is traveling..
how would I do this? (the bullet is #bullet)
I tried doing a loop for this but i must have failed because it didn't work.
Use step option of .animate() , .stop()
var money = $("#thegame span")[0];
$("#bullet").animate({
marginLeft: '100%'
}, {
duration: 1000,
step: function(now, fx) {
// calling `.stop()` triggers `.fail` callback
if (now > 70) $(fx.elem).stop()
},
done: function() {
document.getElementById("thegame").removeChild(money);
},
fail: function() {
document.getElementById("thegame").removeChild(money);
console.log(this, this.style.marginLeft)
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<div id="bullet">abc</div>
<div id="thegame"><span>thegame</span></div>
Use setTimeout()for this purpose,
function myfun(){
setTimeout(function(){$("#welcome").show(100)}, 2000);
setTimeout(function(){$("#welcome").hide(500)}, 7000);
}
setInterval()would invoke the supplied code for every time interval that you gave

Make sure only one animation is being fired

I am running this animation on $(window).scroll() and it works fine for the most part.
$('#el').animate({ left: toMove }, 500);
The problem is if the user scrolls too fast, two animations will fire and the second animation will fire before the first one has moved far enough. How can I make sure there is only one animation at any given time and then the other animations will follow? I need the element to animate left FULLY any other animations run but I need them all to run. I tried using .queue() but couldn't find the right solution with it.
You could use the stop function like this to smooth things up:
$('#el').stop(true, false).animate({ left: toMove }, 500);
The stop function, when calling like that will clear the animation queue for any waiting animation, as well as stop the current animation if any.
Edit
If you want the animation to end before animating again you just need to call .stop(true, true) instead

.fadeIn() / fadeOut() on mousemove

I got a problem with smooth fadeIn and fadeOut in mousemove... I am doing some calculations about what is under top element, and based on those calculations I would like to fadeIn() or fadeOut() tooltip. The problem is that when moving a mouse, events are being shoot like every few milliseconds.
The sitiuation looks like this:
I move the mouse, tooltip is hidden. Suddenly mouse pointer is on top of element that should trigger fadeIn(), but this element is not the triggerer, because it is behind of some other element. So I need to shoot fadeIn() from mousemove. But, when I shoot it, every few milliseconds, it doesn't work, or works million times. But generally, it does not... animation simply stucks as long as I move mouse, because fadeIn() is being called all over again. I am really tired of this, tried to fix it for like 5 hours and nothing.
I've tried:
.stop() before fadeIn() / fadeOut() in different configurations... but the only visible effect I got was that it looked like show(), because stop(true,true) simply deletes the queue and leads to the end of last animation. So, wow! It is show... how... eghn... great :/
Using :visibe selector to fadeOut() and :not(:visible) to fadeIn() ... well.. that of course did not change much, an with stop() it was just leaving semitransparent tooltip
Using rel attribute to define that the fadeOut() was already shoot and should not be shoot anymore... even worse idea, because it simply did not come back after total fadeOut()
To get some reset and thing, but I can't rest when I don't have this problem resolved - it is sooo annoying!
I wonder if anybody reads this anyway... I wouldn't.
So HOW to limit fadeOut(), fadeIn() events to one each time so it would smoothly fadeIn and fadeOut even from middle of animation when event is triggered by mousemove?
I will probably get -1000 for this question... doooh.
I'd suggest you use css for this instead. You lose a bit of compatibility (Most notably older IE's), but it's simpler and will run a lot smoother.
E.g. define opacity in a :hover pseudo class, and then define a transition property with a timing of your choice.
Edit:
Using css in this case has no use because as I said, the event is not trigered by top most layer... stop(true,true) works exactly te same as show() because it is called every few milliseconds, and once is enough to stop fade effect.
In that case, set/unset a class on the fading-element inside your event handler. Let css do the work for you.
E.g.:
<style>
#tooltip { opacity:0 ; transition:opacity 1s linear }
#tooltip.enabled { opacity:1 }
</style>
<div class="has-tooltip">Foo</div>
<div id="tooltip">Tooltip</div>
<script>
$(".has-tooltip")
.on("mouseenter", function() { $("#tooltip").addClass("enabled") })
.on("mouseleave", function() { $("#tooltip").removeClass("enabled") })
</script>
You can try to unbind events before FadeIn/fadeOut and bind again after animation is complete (in complete function).
try this, call this function on mouse move
TIMER='';
function onmove()
{
if(TIMER)
clearTimeout(TIMER);
else
TIMER = setTimeout(function(){
// use yor code here eg. $('whteverID').fadeIn();
},10)
}

jQuery Queue Functions

Take these two methods:
function moveUp() {
this.element.rotate(0);
this.element.animate({"margin-top": "-=51px"}, "slow");
//do some more things for instance.
}
function moveRight() {
this.element.rotate(90);
this.element.animate({"margin-left": "+=51px"}, "slow");
}
Just in case, I rotate an object, then move it around with an animation. These functions are mapped to key presses, so if the user presses Up or Right, the object moves. My problem is that the animations are queued properly, because jQuery uses the fx queue for them. But the rotation happens inmediately, as well as any other thing I do, since they are custom things I have in my code.
The consequence is obvious, if you press say up and immediately press right, the object rotates up, but while it is moving upwards, it rotates right, it doesn't really wait until it gets there.
How can I write this code so that the whole methods are chained and not just their animations. I could add callbacks, but they won't always execute together, I need them to be queued if they happen to be called simultaneously, but I don't quite understand how to use the queue functionality in jQuery.
By the way, to see more of the code behind this, I have recently asked this question also: Array of prototype functions
You could animate it using something like:
$elem.animate({rotation: 90},
{
duration: 'slow',
step: function(now, fx) {
$(this).css({ "transform": "rotate("+now+"deg)", "-webkit-transform": "rotate("+now+"deg)", "-moz-transform": "rotate("+now+"deg)" });
}
})
That would add it to the queue automatically
I've made a jsfiddle here:
http://jsfiddle.net/obartra/7Qwgd/1/
EDIT: Just to explain my rationale, I'm guessing that the rotate method you are using is using setTimeout to set the rotation in the CSS progressively, thus not adding it to the animation queue. The code here uses animate to rotate the element so it gets added to the animation queue.

how to execute multiple animations simultaneously in mootools?

I have two divs (say, divs with ids: div1 and div2) whose height I need to expand using Fx.Tween
And I want the animations to be simultaneous.
'#div1' 's style.height is to be changed from auto to 0.
'#div2' 's style.height is to be changed for current height to a new height calculated by a function called calculateHeight()
how do I do that?
Mootools animations aren't blocking (animations in JS very rarely are!) so simply executing the two tweens sequentially will have the desired affect (as close as a human can perceive)
function go()
{
$('div1').tween('height', 0);
$('div2').tween('height', calculateHeight());
}
function calculateHeight()
{
return 0; //or whatever
}
I think this has to do with the wait:false option.
I'm not a programmer and mootools is easy but not as much to be so good at it but I remember reading some docs where it says you can control wether the second animation works as soon as the first one ends or simultaneously.
Chain Method: wait
Injects pauses between chained events.
Syntax
myClass.wait(duration);
Arguments
1. duration - (integer) The duration (in milliseconds) to pause the chain stack; defaults to 500.
I think you should CHAIN the morphing and make it wait(0). But I'm not sure. Hope this helps.

Categories