I have a jsFiddle that I've been messing around with, trying to get my little game to become more organized with classes and such, but when I request an animation frame, passing in the objects (each frame does a few functions with each object), I get a Maximum call stack size error. How can I fix this without abandoning my classes?
The jsFiddle: http://jsfiddle.net/Blawkbuilder/Q5U3X/109/
the line I suspect to be the culpurit:
window.requestAnimationFrame(draw(p1,p2));
but the line the console links to occurs somewhere in jquery:
} else if ( !rhtml.test( elem ) ) {
Fix? I'm a bit new to javascript.
(If needed, here is the previous, not class based version that still functions how I want this too) http://jsfiddle.net/Blawkbuilder/9hmca/131/
requestAnimationFrame takes a callback. You are evaluating draw(p1, p2) and passing its return value to requestAnimationFrame. You should change to something like this:
requestAnimationFrame(function() { draw(p1, p2); });
This is similar to setInterval/setTimeout.
requestAnimationFrame takes a callback function with no arguments as a parameter. The reason you're getting a stack overflow is that you're providing the parameter draw(p1, p2) (rather than draw), which actually invokes the draw function, which then makes the same mistake of invoking the draw function ... (and so forth). You're doing it correctly in the second jsFiddle.
To get around this, you need draw to not take any parameters. Alternatively, create a "wrapper" function that doesn't take any parameters, which itself simply invokes draw with the appropriate parameters. The simplest way to do this do something like requestAnimationFrame(function() {draw(p1, p2); }) as the other answer suggests.
By the way, telling you this is metaphorically giving you a fish, rather than teaching you how to fish. To really understand this, you need to understand a bit more about functional programming, which can get a little abstract. In this example, understand that functions are nothing more than objects that have the special property of being "callable" (or "invokable"). requestAnimationFrame is a function whose first parameter, callback, is another function. requestAnimationFrame is expecting that callback is callable, in other words. But you're giving it the result of calling the function, rather than the function itself.
The reason function() {draw(p1, p2);} works is that the function() { ... } syntax constructs an anonymous function -- a function without a name, but still a function that can be invoked.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With