2

This is my first question on StackOverflow, so forgive any breaches in protocol.

I'm learning WebGL in a computer graphics class in college. While learning to make a square rotate on the screen, my classmates and I noticed the following code in the render function:

function render() 
{ 
 gl.clear(gl.COLOR_BUFFER_BIT); 
 theta += 0.1; 
 gl.uniform1f(thetaLoc, theta); 
 gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4); 
 render(); 
}

What we don't understand, and our professor was not able to give us an adequate answer, is why this code does not cause a stack overflow since it calls itself recursively. We ran the code, and it doesn't cause any problems, but we don't understand why.

We weren't able to find an answer to this in our textbook or online. If anyone can explain it, I'll pass it on to my classmates. Thanks in advance.

Lochian
  • 21
  • 2
  • 2
    http://stackoverflow.com/questions/310974/what-is-tail-call-optimization – JAre Oct 15 '14 at 15:20
  • I've never heard of Tail Call Optimization, but the link you provided explained it perfectly. I'll pass on the information. Thanks! – Lochian Oct 15 '14 at 15:33
  • Most likely, your compiler is smart enough to recognize the opportunity for optimization, but with the other one you can get overflow - be careful. On the other hand, functional languages rely heavily on recursion and some of them provide means for explicit tailrec optimization, so it's not like recursion is a bad thing, but it can be dangerous. – JAre Oct 15 '14 at 15:42

1 Answers1

3

That does cause a stack overflow. When I run it I get

Uncaught RangeError: Maximum call stack size exceeded 

I think you probably saw code like this

function render() {
   ...
   requestAnimationFrame(render);
}
render();

In that case it's not recursive. The render function is requesting an animation frame and then exiting. Then the browser renders the next frame it calls render again.

gman
  • 100,619
  • 31
  • 269
  • 393
  • Thanks gman for confirming I'm not crazy. But JAre answered the question for me in the comments by explaining Tail Call Optimization. Apparently your browser doesn't have that optimization, which led to the stack overflow. I appreciate both you and him helping me to understand this issue. – Lochian Oct 17 '14 at 01:01
  • I think only ES6+ has tail call optimization. – JAre Oct 17 '14 at 12:07