所以我已经编写了一些课程代码,代码假设在页面加载时启动一个函数,然后运行在屏幕上更改交通灯图像的功能。假设继续改变,但是当我尝试运行时程序崩溃或无法加载。在您提出问题之前,条件中使用的变量未更改,我尝试在以下代码中更改它。当我在chrome调试器中运行它时,就会出现这种情况; '未捕获的SyntaxError:意外的令牌<'。
<DOCTYPE html>
<html>
<body onload="infinity()">
<p></p>
<h1>Traffic Light Sequence</h1>
<img id ="trafficlight" src="r.jpg">
<script>
var images = [
"r.jpg",
"randy.jpg",
"g.jpg",
"y.jpg"
];
var counter = 0;
function start() {
counter = counter + 1;
if(counter == images.length) counter=0;
var image = document.getElementById("trafficlight");
image.src=images[counter];
}
var a = 100;
function infinity() {
while (200>a) {
setTimeout(start(), 3000);
}
a = a - 25;
}
</script>
</body>
</html>
答案 0 :(得分:0)
我知道这个问题已经有了答案,但我只是认为以下代码可能是更好的,也是一种相对简单的方法。
<DOCTYPE html>
<html>
<body onload="infinity()">
<p></p>
<h1>Traffic Light Sequence</h1>
<img id ="trafficlight" src="r.jpg">
<script>
var images = [
"red.JPG",
"green.jpg",
"randy.jpg",
"yellow.JPG"
];
function infinity() {
var counter = 0,
image = document.getElementById("trafficlight"),
a = 5,
timeoutInterval = 3000;
setInterval(function() {
counter++;
if(counter == images.length) counter=0;
if (a>=0) {
image.src=images[counter];
a--;
}else{
// this else case is in the event that the timeout
// variable is 1, which is essentially 1ms, which
// is bad as it would make your cpu usage go to a
// 100%
if (timeoutInterval <= Number.MAX_SAFE_INTEGER - 2) {
// the above if condition is to stop timeoutInterval
// from ever reaching 2^53 which would cause an
// overflow
timeoutInterval *= 2;
Math.pow(timeoutInterval, 20);
}
}
}, timeoutInterval);
}
</script>
</body>
</html>
谢谢!
P.S。我的笔记本电脑在运行你的无限循环代码
时仍然很热