rtheunissen
rtheunissen

Reputation: 7435

How to allow arbitrary 'update' functions to be passed to a requestAnimationFrame loop?

Here is what I have at the moment:

function animateLetter(letter, type){
    letter.css(type, '50%');
    var j = 50;
    loop(function(){
    letter.css(type, (j =- 5) + '%'); 
    return j < 0;
    });
   }

   function loop(run) {
       if(run.apply()) requestAnimationFrame(loop(run));
   }

Why would this not work? I'm new to JS so might be missing something obvious.

Upvotes: 2

Views: 39

Answers (1)

steveukx
steveukx

Reputation: 4368

The loop function causes an infinite loop as it calls itself in the invocation of requestAnimationFrame.

function loop(run) {
   if(run.apply()) requestAnimationFrame(function() { loop(run) });
}

Wrapping the call to loop in another function means that it will only be called when the requestAnimationFrame callback is called.

Upvotes: 4

Related Questions