我在 javascript 中创建了这个无限循环,以便运行 setTimeout 函数。问题是,通过这样做,我的页面甚至没有首先加载。
这是javascript代码:
function blurDiv() {
console.log("here");
rankingList.style.filter="blur(0.7)";
}
function loadContent() {
console.log("loaded");
$( "#ranking-container" ).load("index.php #ranking-list");
rankingList.style.filter="blur(0)";
}
while(true) {
setTimeout(blurDiv, 4000);
setTimeout(loadContent, 5000);
}
我原以为循环只会在这 5 秒后运行另一次迭代。
使用setInterval()
代替while(true){setTimeout()}
function blurDiv() {
console.log("here");
// Other stuff here
}
function loadContent() {
console.log("loaded");
// Other stuff here
}
setInterval(blurDiv, 5000);
setInterval(loadContent, 5000);
解释:
setTimeout()
是一个异步函数,这意味着 JS 不会等待它完成并继续运行。因此,使用 loop while(true)
,它会在每一轮中创建两个超时回调,这将导致大量(非常大量)的超时回调并且永远不会退出该while(true)
循环。
但是,通过使用setInterval()
您可以创建一个计时器,它将在每个周期(间隔)中触发回调。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句