Search code examples
javascriptout-of-memory

JavaScript Code gives out of memory exception


i have an issue with javascript. var startTime = Date.now(); while ((Date.now() - startTime) < 30000) { display(); } when i adding these lines of code and trying to run my script,it gives me an error: out of memory.

my original code is:

<script>
   var startTime = Date.now();
while ((Date.now() - startTime) < 30000) {
    display();
}
        function display() {
            setTimeout(showLeft, 1000);
            setTimeout(showRight, 2000);
            setTimeout(showBLeft, 3000);
            setTimeout(showBRight, 4000);
            setTimeout(clearAllDiv, 6000);
        }

        function showLeft() {
            document.getElementById("left").innerHTML = "Hızlı";
        }
        function showRight() {
            document.getElementById("right").innerHTML = "Oku";
        }
        function showBLeft() {
            document.getElementById("bleft").innerHTML = "Çabuk";
        }
        function showBRight() {
            document.getElementById("bright").innerHTML = "Anla";
        }

        function clearAllDiv() {
            document.getElementById("left").innerHTML = " ";
            document.getElementById("right").innerHTML = " ";
            document.getElementById("bleft").innerHTML = " ";
            document.getElementById("bright").innerHTML = " ";
        }
    </script>

i want to repeat my display function for 30 seconds. when i change 30.000 to 1.000 it works fine,but i need 30 seconds not 1 second.

EDIT: i was creating infinite loop,and due this reason i got out of memory exception.


Solution

  • you have created an infinite loop. maybe something more like this:

    var startTime = Date.now();
    checkTimer(startTime);
    
    function checkTimer(startTime) {
        if(((Date.now() - startTime) < 30000)) {
          display();
          setTimeout(() => {
            checkTimer(startTime)
          }, 1000);
        }
    
    }