JavaScript代码给出内存不足异常

dhxwm5r4  于 2023-04-04  发布在  Java
关注(0)|答案(2)|浏览(201)

我有一个javascript.var startTime = Date.now(); while ((Date.now() - startTime) < 30000) { display(); }的问题,当我添加这些代码行,并试图运行我的脚本,它给了我一个错误:内存不足。
我的原始代码是:

<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>

我想重复我的显示功能30秒。当我把30. 000改成1. 000时效果很好,但我需要30秒而不是1秒。
编辑:我正在创建无限循环,由于这个原因,我得到了内存异常。

nsc4cvqm

nsc4cvqm1#

你已经创建了一个无限循环。也许更像这样:

var startTime = Date.now();
checkTimer(startTime);

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

}
bf1o4zei

bf1o4zei2#

你的while循环阻塞了定时器回调的异步执行,同时你的循环创建了一个巨大数量的定时器,耗尽了内存。
相反,您可以安排display调用,如下所示:

// Execute display 4 times, but only at the right time
display();
setTimeout(display, 8000);
setTimeout(display, 16000);
setTimeout(display, 24000);

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 = " ";
}
<div id="left"></div>
<div id="right"></div>
<div id="bleft"></div>
<div id="bright"></div>

相关问题