Javascript怎么实现红绿灯
4693
javascript实现红绿灯的方法:1、使用setTimeout和递归来实现循环改变颜色;2、使用Promise,并把下一次的颜色改变写在then里面;3、使用async await和while实现红绿灯效果。
JavaScript 实现红绿灯
使用setTimeout、Promise、async await 三种方式实现红绿灯代码,红灯2秒,黄灯1秒,绿灯3秒,循环改变颜色。改变颜色的方法,就简单写成打印出颜色。
setTimeout实现
使用setTimeout是最基本的实现方式,代码如下,使用递归来实现循环改变颜色。
- function changeColor(color) {
- console.log('traffic-light ', color);
- }
- function main() {
- changeColor('red');
- setTimeout(()=>{
- changeColor('yellow');
- setTimeout(() => {
- changeColor('green');
- setTimeout(main, 2000);
- }, 1000);
- }, 2000);
- }
- main();
Promise 实现
使用Promise,把下一次的颜色改变写在then里面,最后同样使用递归完成循环。
- function sleep(duration){
- return new Promise(resolve => {
- setTimeout(resolve, duration);
- })
- }
- function changeColor(duration,color){
- return new Promise(resolve => {
- console.log('traffic-light ', color);
- sleep(duration).then(resolve);
- })
- }
- function main() {
- return new Promise(resolve => {
- changeColor(2000, 'red').then(() => {
- changeColor(1000, 'yellow').then(() => {
- changeColor(3000, 'green').then(() => {
- main();
- })
- })
- })
- })
- }
- main();
async await 实现
使用async await就可以避免Promise的一连串.then.then.then,也不再需要递归,使用while就可以实现循环。
- function sleep(duration) {
- return new Promise(resolve => {
- setTimeout(resolve, duration);
- })
- }
- async function changeColor(color, duration) {
- console.log('traffic-light ', color);
- await sleep(duration);
- }
- async function main() {
- while (true) {
- await changeColor('red', 2000);
- await changeColor('yellow', 1000);
- await changeColor('green', 3000);
- }
- }
- main();
本文网址:https://www.zztuku.com/detail-10038.html
站长图库 - Javascript怎么实现红绿灯
申明:如有侵犯,请 联系我们 删除。
您还没有登录,请 登录 后发表评论!
提示:请勿发布广告垃圾评论,否则封号处理!!