requestAnimationFrame not waiting for the next frame

Thanks for checking in!

So as far as I know (it may be wrong) JavaScript's requestAnimationFrame method works (a little bit) like setTimeout except it doesn't wait for a certain amount of time but for the next frame to be rendered.

This can be used for a lot of things, but what I'm trying to achieve here is a CSS based JavaScript controlled fade effect. Here is what the code looks like with explanation:

//This line makes the element displayed as block from none
//but at this point it has an opacity value of 0
this.addClass('element__displayed');

//here i am waiting a frame so that the previously added
//display value takes effect
window.requestAnimationFrame(function(){
    //adding opacity: 1 for fade effect
    this.addClass('element__visible');
}.bind(this));

My problem here is that even though the element has its css transition set up and I am waiting for the display value to be rendered, I am getting no transition, it just pops in.

(it works if I use setTimeout(..., 1000/60), but setTimeout is a performance bottleneck compared to requestAnimationFrame)

Please don't try to give an alternate solution for a fading effect because the my question is not the effect, but why the animationFrame isn't working!

Thank you!

Upvotes: 4

Views: 2918

Answers (1)

ernesto
ernesto

Reputation: 1818

I think requestAnimationFrame is not guaranteed to wait for the next frame. Paul Irish writes

Any rAFs queued in your event handlers will be executed in the ​same frame​. Any rAFs queued in a rAF will be executed in the next frame​.

If adapted your demo, it works for me now on Chrome: https://jsfiddle.net/ker9zpjs/

I once found this helper which is in my toolbox since then:

var nextFrame = function(fn) { raf(function() { raf(fn); }); };

But I must confess that my answer is not fully researched, if somebody could find better information, I would also appreciate it.

Upvotes: 4

Related Questions