这是我正在尝试的网站的一小部分。无论如何我正在学习Javascript,我决定通过制作一个非常简单的“幻灯片”进行实验,但每当我在浏览器(Mozilla Firefox 42)中运行它时,浏览器就会崩溃。我想知道是否有人可以告诉我什么是错的或者可能给我一个更好的方法来制作它(我确信有,但我找不到一个)。另外我知道我可以用jQuery做这个,但我想用纯Javascript试试这个。
我也在Chrome和Opera上试过这个。
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
//I will use javascript to make the "slideshow" on mainSection
function loop() {
var BACKGROUND = document.getElementById("Introduction");
var SECTION1 = document.getElementById("mainSection");
var SECTION2 = document.getElementById("section2");
var SECTION3 = document.getElementById("section3");
var i = 1;
while (i <= 3) {
i = i + 0.0001;
SECTION1.style.display="block";
SECTION2.style.display="none";
SECTION3.style.display="none";
}
while (i <= 6) {
i = i + 0.0001;
SECTION1.style.display="none";
SECTION2.style.display="block";
SECTION3.style.display="none";
}
while (i <= 9) {
i = i + 0.0001;
SECTION1.style.display="none";
SECTION2.style.display="none";
SECTION3.style.display="block";
}
while (i = 9) {
i = 1;
}
}
</script>
</head>
<body onload="loop();">
<header id="Introduction">
<section id="mainSection">
<h1>Welcome to the Ipsum Hotel.</h1>
<p>This is where thought and precision goes<br />
towards the comfort of our customers.<br /></p>
</section>
<!--This will be used to make a slideshow-->
<section id="section2">
<p><strong>Free Wifi!</strong></p>
<p>Free wifi is included in all of our guest<br />
packages from Economy to Deluxe<br /></p>
</section>
<section id="section3">
<p><strong>Free Hot Breakfast</strong></p>
<p>Included with any of our guest packages is<br />
a hearty breakfast. You can also get a personalized<br />
omelet at our omelet bar.<br /></p>
</section>
</header>
</body>
</html>
答案 0 :(得分:0)
尝试使用setInterval
。正如评论中所提到的,while循环将阻止所有页面操作并对CPU征税。 setInterval
专门用于以更加资源友好的方式处理计时操作。
var SECTION1 = document.getElementById("mainSection");
var SECTION2 = document.getElementById("section2");
var SECTION3 = document.getElementById("section3");
var sections = [SECTION1, SECTION2, SECTION3];
var activeSection = 0;
setInterval(function() {
// If we are past the end of list, reset to first element
if (activeSection >= sections.length) {
activeSection = 0;
}
// Mark only the activeSection as visible
sections.forEach(function(section, idx) {
section.style.display = activeSection === idx ? 'block' : 'none';
});
activeSection += 1;
}, 3000);
这将每三秒循环一次每个部分(至少请参阅https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setInterval以获取有关计时器如何在浏览器中工作的更多信息)。到达最后一个部分后,它将重置为第一部分。