我有一个问题与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秒。
编辑:我正在创建无限循环,由于这个原因,我得到了内存不足异常。
你已经创建了一个无限循环。也许更像这样:
var startTime = Date.now();
checkTimer(startTime);
function checkTimer(startTime) {
if(((Date.now() - startTime) < 30000)) {
display();
setTimeout(() => {
checkTimer(startTime)
}, 1000);
}
}
你的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>