jquery - Javascript on ajax keeps growing -


i have site configurable 3d object has properties , change properties reload div 3d object reflect new properties. works fine except script data keeps adding on. not script slows down after 30 reloads, here happens. added rotation object rotation rendering function , every reload button keeps spinning faster! after 5 reloads spins crazy. spinning function simple:

    function animate() {     if (typeof(objektas) !== 'undefined') {         rotation++;         if (rotation >= 360) rotation = 0;         objektas.rotation.y = rotation * math.pi * 2 / 360;     }     requestanimationframe(animate, renderer.domelement);     renderer.render(scene, camera); } 

my guess every load render animate functions stacked , example in second reload called twice instead of once. can explain how can solve issue?

when animate first invoked, continuously re-invoke itself. you're using recursion create continuous loop.

my understanding every time reload, reinvoke animate function. if invoke second time, have 2 continuous animate loops happening, interweaved on same ui thread. rotation variable incrementing twice fast.

call third time, have 3 animate loops. call 30 times, 30 interweaved loops going cause serious performance issues.

the solution: @ place first call it, make sure gets called once.

have global variable:

var hascalledanimate = false; 

and @ place first invoke it:

if(!hascalledanimate) {    hascalledanimate = true;    animate(); } 

if want absolutely 100% sure nobody ever call second time, use closures.

   var animate = (function () {        function _animate() {            if (typeof (objektas) !== 'undefined') {                rotation++;                if (rotation >= 360) rotation = 0;                objektas.rotation.y = rotation * math.pi * 2 / 360;            }            requestanimationframe(_animate, renderer.domelement);            renderer.render(scene, camera);        }        var _hasinvoked = false;        return function () {            if (!_hasinvoked) {                _hasinvoked = true;                _animate();            }        }    })(); 

now animate idempotent - can call many times know loop started once.


Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

Rendering JButton to get the JCheckBox behavior in a JTable by using images does not update my table -