4

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!

kristóf baján
  • 473
  • 1
  • 5
  • 15

1 Answers1

4

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.

ernesto
  • 1,771
  • 2
  • 18
  • 18
  • `Any rAFs queued in a rAF will be executed in the next frame​.` That appears to be a lie. – H.B. Feb 04 '18 at 18:15
  • @H.B.: Do you have any references or examples backing this up? – ernesto Feb 04 '18 at 23:47
  • I had some issue with WebVR, though those might be artifacts from the external device having its own rAF loops. I would have to look into this more deeply, maybe the actual behaviour is not even properly observable using e.g. the Chrome profiler. – H.B. Feb 05 '18 at 16:24
  • Looks like it probably is just be a profiler artifact and actually everything executes as expected. – H.B. Feb 05 '18 at 20:33