promise 实现红绿灯
Posted xiaosongjiang
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了promise 实现红绿灯相关的知识,希望对你有一定的参考价值。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>红绿灯</title> </head> <style> ul { position: absolute; width: 200px; height: 200px; top: 50%; left: 50%; transform: translate(-50%,-50%); } /*画3个圆代表红绿灯*/ ul >li { width: 40px; height: 40px; border-radius:50%; opacity: 0.2; display: inline-block; } /*执行时改变透明度*/ ul.red >#red, ul.green >#green, ul.yellow >#yellow{ opacity: 1.0; } /*红绿灯的三个颜色*/ #red {background: red;} #yellow {background: yellow;} #green {background: green;} </style> <body> <ul id="main" class=""> <li id="green"></li> <li id="yellow"></li> <li id="red"></li> </ul> </body> <script> function timeOut(timer){ return function(){ return new Promise(function(resolve,reject){ setTimeout(resolve,timer) }) } } var green = timeOut(5000); var yellow = timeOut(2000); var red = timeOut(3000); var main = document.getElementById("main"); (function restart(){ ‘use strict‘ //严格模式 console.log("绿灯"+new Date().getSeconds()) //绿灯执行5秒 main.className = ‘green‘; green() .then(function(){ console.log("黄灯"+new Date().getSeconds()) //黄灯执行2秒 main.className = ‘yellow‘; return yellow(); }) .then(function(){ console.log("红灯"+new Date().getSeconds()) //红灯执行3秒 main.className = ‘red‘; return red(); }).then(function(){ restart() }) })(); </script> </html>
以上是关于promise 实现红绿灯的主要内容,如果未能解决你的问题,请参考以下文章
VSCode自定义代码片段12——JavaScript的Promise对象
VSCode自定义代码片段12——JavaScript的Promise对象