sherlock
sherlock

Reputation: 764

requestAnimationFrame seems slow, cancelAnimationFrame not working

This is what I'm working on. If you scroll to JS line 63 you will see the function I am having difficulty with. I am trying to replace my setInterval code (in comments) with requestAnimationFrame. But the animation seems to be going rather slowly, also, it doesn't ever stop!! Here is a working version with setInterval.

Relevant JS:

function setGauge(val){
    var time = 350;
    time = time / (Math.abs(val - preVal));

    if (val > preVal) {
        function getHigher(){
           if (preVal == val)
                cancelAnimationFrame(animate);
            preVal++;
            drawValueArc(preVal);
            var animate = requestAnimationFrame(getHigher);
        }
        getHigher();
        /*
        var animate = setInterval(function(){
            if (preVal == val)
                clearInterval(animate);
            preVal++;
            drawValueArc(preVal);  
        }, time);
        */
    } else if (val < preVal) {
        function getLower(){
           if (preVal == val)
                cancelAnimationFrame(animate2);
            preVal--;
            drawValueArc(preVal);  
            var animate2 = requestAnimationFrame(getLower);
        }
        getLower();
        /*
        var animate2 = setInterval(function(){
            if (preVal == val)
                clearInterval(animate2);
            preVal--;
            drawValueArc(preVal);  
        }, time);
        */
    } 
}

Upvotes: 2

Views: 1886

Answers (1)

user1693593
user1693593

Reputation:

I modified the code just slightly, you where almost there.

The animate and animate2 isn't really needed as we don't cancel the requestAnimationFrame (rAF) but merely check if the condition for it to run is there:

function setGauge(val) {
    var time = 350;
    time = time / (Math.abs(val - preVal));

    if (val > preVal) {
        function getHigher() {
            preVal++;
            drawValueArc(preVal);

            //if still less then rAF again
            if (preVal < val) requestAnimationFrame(getHigher);
        }
        getHigher();

    } else if (val < preVal) {
        function getLower() {
            preVal--;
            drawValueArc(preVal);

            //if still more then rAF again
            if (preVal > val) requestAnimationFrame(getLower);
        }
        getLower();

     //...
}

See modified fiddle here (link seem to:

http://jsfiddle.net/AbdiasSoftware/cUSBQ/11/

Upvotes: 3

Related Questions