题目描述
实现一个红绿灯交替展示的功能,要求红灯亮 3 秒,绿灯亮 2 秒,黄灯亮 1 秒,循环往复。使用 async
和 Promise
实现。
<el-button type="primary" round :style="{'background-color': currentColor}" @click="colorTurn">{{timeNow}}</el-button>
let currentColor = ref('');
let timeNow = ref(1);
let timer = ref<any>(null);
const lightColor = (color: string, time: number) => {
currentColor.value = color;
timeNow.value = 1;
timer.value = setInterval(() => {
timeNow.value++;
}, 1000);
return new Promise((resolve) => {
setTimeout(() => {
clearInterval(timer.value);
resolve(color);
}, time);
});
};
const colorTurn = async () => {
while (true) {
await lightColor('red', 3000);
await lightColor('green', 2000);
await lightColor('yellow', 1000);
}
};
其中setInterval计时器是为了方便看时间间隔的