Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Buggy behavior using requestAnimationFrame

I've wrote a useful library to draw and animate the stroke of SVG paths: segment. You can check it on github.

Some time ago I've replaced (accepting a Pull Request) the setTimeout calls with requestAnimationFrame, to speed up the animation in modern browsers, also using the polyfill provided by Paul Irish.

Now I'm experimenting a buggy behavior with requestAnimationFrame calls when I tried to animate multiple paths with a very low delay among them.

I've prepared 2 demos to show the behavior with both setTimeout (working properly) and requestAnimationFrame (buggy behavior). Check it please:

  • setTimeout Demo
  • requestAnimationFrame Demo

In the requestAnimationFrame Demo, I've modified a bit my library to print in the console some useful info, where you can see the buggy behavior:

(function calc(){
    // Checking if it's the first element, the buggy behavior happens in the firsts elements
    if(that.class === 'first'){
        console.log('calc');
    }

    // Some code here that can break the recursive loop and stop execution of calc function

    if(that.class === 'first'){
        console.log('calc call');
    }
    that.timer = window.requestAnimationFrame(calc);

    // More code here
})();

According to the previous code, after every 'calc call' message should appear a 'calc' message. But that is not what I can see, at least in Firefox and Chrome. This is the console output most of times:

calc
calc call
calc
calc call

I really have no idea what's going on, so any help is welcome :)

like image 462
lmgonzalves Avatar asked Jan 19 '26 11:01

lmgonzalves


1 Answers

The buggy behavior here is being caused because both timeoutID and return value from requestAnimationFrame are being saved into the same variable. Saving them in different variables will fix the issue.

Here is a codepen

http://codepen.io/anon/pen/KzPboY?editors=0010

like image 62
satish Avatar answered Jan 21 '26 00:01

satish



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!