Bastiaan Zwanenburg
Bastiaan Zwanenburg

Reputation: 143

Setinterval animate

I have a problem. I want to check around 50 times per second if some sort of variable is true. If it's true, we need to do a 1sec background transition. I made it like this:

setInterval(
        function(){


            if(var) {
                   $('.side-bar').animate({
                        backgroundColor: "#fff"
                        }, 1000);
            }
            else { 
           $('.side-bar').animate({
                        backgroundColor: "#000"
                        }, 1000);
            }   
            },20);

The problem is that if var is true, for some sort of reason the animate will get stuck, and it can't change anymore. If we make the intervaltime bigger than the animation time (So interval 1001 and animate 1000 for example), it does work. When intervaltime < animationtime, it doesn't work. Who knows a solution for this?

Upvotes: 0

Views: 1310

Answers (1)

nnnnnn
nnnnnn

Reputation: 150070

Every time your function runs, it tries to start one or the other of your two animations. jQuery queues the subsequent animation calls. So after one second when your function has run 50 times, you have queued 50 animations, the first one of which would be just about finished.

I don't really recommend doing that sort of polling on a variable, it would be better to trigger the animation directly from whatever code sets the variable, but to get past your current problem you could check whether there is currently an animation in progress and if so do nothing:

setInterval(function () {
    var $sidebar = $('.side-bar');
    if ($sidebar.is(':animated')) return;
    if (condition) {
        $sidebar.animate({
            backgroundColor: "#fff"
        }, 1000);
    } else {
        $sidebar.animate({
            backgroundColor: "#000"
        }, 1000);
    }
}, 20);

Demo: http://jsfiddle.net/yXWPD/

But even then you'd still be continuously re-animating the same thing, you just wouldn't be queuing more than one animation at a time. There's no need to queue another animation unless the condition variable has actually changed:

var condition = false; // your condition var, that is set true by some
                       // other code somewhere

var prevCondition,
    $sidebar = $('.side-bar');
setInterval(function () {
    if (prevCondition != condition && !$sidebar.is(':animated')) {
        prevCondition = condition;
        $sidebar.animate({
            backgroundColor: condition ? "#fff" : "#000"
        }, 1000);
    }
}, 20);

Demo: http://jsfiddle.net/yXWPD/2/

But again, this polling concept isn't the best way to go. You should trigger the animation from the code that changes the variable.

Upvotes: 1

Related Questions