title: Strange JavaScript Loop Happening with Three.Js
body: <p>I am building a prototype SPA with Angular and Three.Js to learn both technologies. I have a few Angular templates that are selectable via a nav, and show different 3D elements rotating. </p>
  
  <p>The cube element is exhibiting strange behaviour; when you navigate to another tab and then navigate back, its rotation speed is increased. This is not happening with the other 3D elements, and I can't figure out why. </p>
  
  <p><a href="http://playground.eca.ed.ac.uk/~s1463054/threejs-prototype/index.html#/" rel="nofollow">Here is a link to the project</a>.</p>
  
  <pre><code>// CUBE ROTATION VALUES
  var cubeRotationX = .005;
  var cubeRotationY = .005;
  
  // CUBE SIZE VALUE
  var cubeSize = 1;
  
  // LOAD A CUBE
  var geometry = new THREE.BoxGeometry( cubeSize, cubeSize, cubeSize );
  var material = new THREE.MeshPhongMaterial  ( { color: 0xEDEDED, } );
  var cube = new THREE.Mesh( geometry, material );
  
  // CUBE CHANGE SIZE FUNCTION
  function changeCubeSize() {
      cubeSize = document.getElementById('size-selector').value;
  }
  
  // CUBE TOGGLE FUNCTION
  function toggleCubeRotation() {
      if (cubeRotationX &gt; 0) {
          cubeRotationX = 0;
          cubeRotationY = 0;
      } else {
          cubeRotationX = 0.005;
          cubeRotationY = 0.005;
      }
  }
  
  // RENDER
      function render() {
          requestAnimationFrame( render );
          cube.rotation.x += cubeRotationX;
          cube.rotation.y += cubeRotationY;
          renderer.setSize( width, height );
          renderer.render( scene, camera );
      }
  </code></pre>
  
  <p>Obviously, when navigating away from, and then back to, the cube page, Angular runs this code again. </p>
  
  <p>After testing, I can confirm that cubeRotationX and cubeRotationY are their correct values (0.005). So it would seem that the loop is coming from cubeRotationX and cubeRotationY being added multiple times to cube.rotation.x and cube.rotation.y, but the loop happens EVEN IF I specifically prohibit these two lines from ever running more than once:</p>
  
  <pre><code>if (typeof code_happened === 'undefined') {
          window.code_happened = true;
          render();
      } else {
          function reRender() {
              requestAnimationFrame( render );
              renderer.setSize( width, height );
              renderer.render( scene, camera );
          }
          reRender();
         }
  </code></pre>
  
  <p>Seriously, I know this is something simple, but I cannot for the life of me figure it out. Any help is greatly appreciated. </p>