jquery - Strange JavaScript Loop Happening with Three.Js -
i building prototype spa angular , three.js learn both technologies. have few angular templates selectable via nav, , show different 3d elements rotating.
the cube element exhibiting strange behaviour; when navigate tab , navigate back, rotation speed increased. not happening other 3d elements, , can't figure out why.
// cube rotation values var cuberotationx = .005; var cuberotationy = .005; // cube size value var cubesize = 1; // load 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 > 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 ); }
obviously, when navigating away from, , to, cube page, angular runs code again.
after testing, can confirm cuberotationx , cuberotationy correct values (0.005). seem loop coming cuberotationx , cuberotationy being added multiple times cube.rotation.x , cube.rotation.y, loop happens if prohibit these 2 lines ever running more once:
if (typeof code_happened === 'undefined') { window.code_happened = true; render(); } else { function rerender() { requestanimationframe( render ); renderer.setsize( width, height ); renderer.render( scene, camera ); } rerender(); }
seriously, know simple, cannot life of me figure out. appreciated.
as suggested 2pha, in case needed happen call
cancelanimationframe( id );
for working threejs , angular templates in future, ammended "only-execute-once" function this:
if (typeof code_happened === 'undefined') { window.code_happened = true; render(); } else { function rerender() { cancelanimationframe( cuberender ); cuberender = requestanimationframe( render ); renderer.setsize( width, height ); renderer.render( scene, camera ); } rerender(); }
this way, when returning page, existing render cancelled , new 1 created. might better end render upon leaving template, far know, threejs doesn't render in background anyways.
Comments
Post a Comment