题目:写一个路口红绿灯,现在正对前方是红灯,从20秒开始倒计时,当数值到0时转成绿灯,绿色灯限时20秒,当数值到0时转成黄灯并重新开始倒数3秒,经过3秒的等待,转成红灯20秒,循环往复以上过程
代码:1.1
<body>
<!-- 写一个路口红绿灯,现在正对前方是红灯,从20秒开始倒计时,当数值到0时转成绿灯,绿色灯限时20秒,
当数值到0时转成黄灯并重新开始倒数3秒,经过3秒的等待,转成红灯20秒,循环往复以上过程 -->
<button>关闭定时器</button>
<script>
// 1.1
var time = 43;
var time1 = 20;
var time2 = 3;
var time3 = 20;
var timer = setInterval(function() {
time--;
if (time >= 23) {
console.log(('绿灯' + time1 + '秒'));
time1--;
if (time1 <= 0) {
time1 = 20
}
} else if (time >= 20) {
console.log(('黄灯' + time2 + '秒'));
time2--;
if (time2 <= 0) {
time2 = 3
}
} else if (time >= 0) {
console.log(('红灯' + time3 + '秒'));
time3--;
if (time3 <= 0) {
time3 = 20
}
} else {
time = 43;
}
}, 100)
var btn = document.querySelector('button');
btn.onclick = function() {
clearInterval(timer)
}
</script>
1.2
<body>
<button>关闭定时器</button>
<script>
var stop = setInterval(a, 100);
var count = 30;
function a() {
count-- ;
console.log(count);
if (count == 0) {
console.log('绿灯到了 ');
clearInterval(stop);
var count1 = 30;
function b() {
count1--;
console.log(count1);
if (count1 == 0) {
console.log('黄灯到了 ');
clearInterval(stop1);
var count2 = 3;
function c() {
count2--;
console.log(count2);
if (count2 == 0) {
console.log('红灯到了 ');
clearInterval(stop2);
var count3 = 30;
function d() {
count3--;
console.log(count3);
if (count3 == 0) {
console.log('绿灯到了 ');
clearInterval(stop3); // var count = 8;
count = 30;
stop = setInterval(a, 100);
}
}
}
var stop3 = setInterval(d, 100)
}
var stop2 = setInterval(c, 100)
}
}
var stop1 = setInterval(b, 100)
}
}
var btn = document.querySelector('button');
btn.onclick = function() {
clearInterval(stop)
}
</script>