红灯3秒亮一次,绿灯2秒亮一次,黄灯1秒亮一次;如何让三个灯不断交替重复亮灯?
要求:用Promise实现
三个亮灯函数已经存在:
1function red() { 2 console.log('red'); 3} 4function green() { 5 console.log('green'); 6} 7function yellow() { 8 console.log('yellow'); 9}
参考答案:
1function red() { 2 console.log("red"); 3} 4function green() { 5 console.log("green"); 6} 7function yellow() { 8 console.log("yellow"); 9} 10const light = function (timer, cb) { 11 return new Promise(resolve => { 12 cb() 13 setTimeout(() => { 14 resolve() 15 }, timer) 16 }) 17} 18const step = function () { 19 Promise.resolve().then(() => { 20 return light(3000, red) 21 }).then(() => { 22 return light(2000, green) 23 }).then(() => { 24 return light(1000, yellow) 25 }).then(() => { 26 return step() 27 }) 28} 29 30step(); 31
最近更新时间:2024-03-18