Detailed explanation of using Promise to implement traffic lights in JS
This article introduces you to the use of Promise in JS to achieve traffic light effects through example code. In the article, I introduce you to an example of promise usage. Friends who need it can refer to it. I hope it can help you.
Requirements
Use promise to realize the jump of traffic light color
After the green light is executed for three seconds
After the yellow light is executed for four seconds
The red light is executed for five seconds
html is implemented as follows:
Define an empty class, and then operate the corresponding class name in js to achieve related effects.
CSS is implemented as follows:
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;}
Javascript principle:
The promise function is an asynchronous operation function, and the then() method can be used at the end of the function. We can achieve this by setting delayed execution inside the promise function.
js code is as follows:
function timeout(timer){ return function(){ return new Promise(function(resolve,reject){ setTimeout(resolve,timer) }) } } var green = timeout(3000); var yellow = timeout(4000); var red = timeout(5000); var traffic = document.getElementById("traffic"); (function restart(){ 'use strict' //严格模式 console.log("绿灯"+new Date().getSeconds()) //绿灯执行三秒 traffic.className = 'green'; green() .then(function(){ console.log("黄灯"+new Date().getSeconds()) //黄灯执行四秒 traffic.className = 'yellow'; return yellow(); }) .then(function(){ console.log("红灯"+new Date().getSeconds()) //红灯执行五秒 traffic.className = 'red'; return red(); }).then(function(){ restart() }) })();
Demo please click here!
ps: Let’s look at an example of Promise usage
Note: If you want the then method to be chainable If the formula continues to be executed, the Promise object must be returned! ! !
'use strict'; function async(value) { return new Promise(function(resolve, reject) { var ms = Math.round(Math.random() * 1000); setTimeout(function() { console.log('waiting ' + ms + 'ms'); // 等待ms毫秒 resolve(value + ms); }, ms); }); } // 每次执行随机等待n毫秒,结果统计总毫秒数 async(0) .then(async) .then(async) .then(async) .then(async) .then(function(value) { console.log('------total wait:' + value + 'ms'); }); //////////////////////////////////////////////////////////// function async1(value) { return new Promise(function(resolve, reject) { resolve(value + 1); }); } function async2(value) { // return new Promise(function(resolve, reject) { // resolve(value + 2); // }); // 等价与上面写法 return Promise.resolve(value + 2); } function async3(value) { return new Promise(function(resolve, reject) { resolve(value + 3); }); } async1(100).then(async2).then(async3).then(function(value) { console.log('------' + value); }); ///////////////////////////////////////////////////////////////// function say() { var value = 'what'; return Promise.resolve(value); } say().then(function(value) { value = value + ' are'; return Promise.resolve(value); }).then(function(value) { value = value + ' you'; return Promise.resolve(value); }).then(function(value) { value = value + ' doing'; return Promise.resolve(value); //return Promise.reject('error, exit'); // 中途退出 }).then(function(value) { value = value + ' now!'; return Promise.resolve(value); }).then(function(value) { console.log('------' + value); }).catch(function(error) { console.log('------' + error); }); <title>Ball move</title> <style> .ball { width: 40px; height: 40px; border-radius: 20px; margin-left: 10px; } .ball1 { background: #ff0000; } .ball2 { background: #00ff00; } .ball3 { background: #0000ff; } </style> <script></script> <p></p> <p></p> <p></p> <script> function moving(ball, pos) { return new Promise(function(resolve, reject) { var marginLeft = parseInt(ball.css('margin-left')); if (marginLeft != pos) { var timerId = setInterval(function() { marginLeft = marginLeft + 1; ball.css('margin-left', marginLeft); if (marginLeft == pos) { clearInterval(timerId); resolve(); } }, 20); } else { resolve(); } }); } moving($('.ball1'), 100).then(function() { return moving($('.ball2'), 150); }).then(function() { return moving($('.ball3'), 200); }); </script>
Related recommendations:
Detailed explanation of the sequential execution of promsie.all and promise in the WeChat applet
Specific usage of jQuery's Promise
Promise, Generator (generator), async (asynchronous) function usage
The above is the detailed content of Detailed explanation of using Promise to implement traffic lights in JS. For more information, please follow other related articles on the PHP Chinese website!

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version
Useful JavaScript development tools