JVE999
JVE999

Reputation: 3517

running requestAnimationFrame from within a new object

I'm having trouble running an animation. This is inside var ob1 = function() {};. When called, it runs for a while and then I get the error Uncaught RangeError: Maximum call stack size exceeded. However, this same structure has no problems running outside of the object.

/////////////// Render the scene ///////////////
this.render = function (){

        renderer.render(scene,camera);
        if(isControls == true) controls.update(clock.getDelta());
        this.animate();
        //console.log(true);
        requestAnimationFrame(this.render());
}

/////////////// Update objects ///////////////
this.animate = function (){
        console.log("!");
}

Upvotes: 9

Views: 5523

Answers (2)

Joseph Astrahan
Joseph Astrahan

Reputation: 9072

Something I did to get this to run from a class that I saw from another example was to do this.

requestAnimationFrame(() => {
      this.animate()
})

This seems to get around the issue as well without any issues!

Here is a threeJS example of me using this from within a class

https://jsfiddle.net/gentleman_goat66/o5wn3bpf/107/

Upvotes: 0

bfavaretto
bfavaretto

Reputation: 71918

You should pass a function reference to requestAnimationFrame, not invoke the function:

requestAnimationFrame(this.render);

Since you're using this inside render, you'll probably need bind:

requestAnimationFrame(this.render.bind(this));

Your version is causing a Stack Overflow (the function is calling itself synchronously, until the call stack is full).


Upvotes: 24

Related Questions