摘要:
下文讲述js实现红绿灯效果的方法分享,如下所示:
实现思路:
1.使用setinterval 重复调用颜色输出函数
2.使用promise实现
例:
//使用setInterval实现循环调用函数
var n = 0;
function setRYG () {
if (n % 3 == 0) { console.log('red') }
else if (n % 3 == 1) { console.log('yellow') }
else { console.log('green') }
n++;
}
setInterval(function () { setRYG() },3000);
//使用Promise实现红绿灯效果
async function showInfo (color, duration) {
console.log(color)
await new Promise(function (resolve) {
setTimeout(resolve, duration);
})
}
async function main () {
while (true) {
await showInfo('red', 1000)
await showInfo('yellow', 2000)
await showInfo('green', 5000)
}
}
main();