Using Promise in JS to implement traffic light example code (demo)
This article introduces you to the use of Promise in JS to achieve traffic light effects through example code. It also introduces an example of promise usage. Friends who do not know how to use Promise in JS can refer to this article
Requirements
Use promise to realize the jump of traffic light color
The green light is executed for three seconds After
After the yellow light is executed for four seconds
The red light is executed for five seconds
html implementation As follows:
<ul id="traffic" class=""> <li id="green"></li> <li id="yellow"></li> <li id="red"></li> </ul>
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;}
javascriptPrinciple:
The promise function is an asynchronous operation function that ends after the function runs You can use the then() method. 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() }) })();
ps: Let’s look at an example of Promise usage
Note: If you want the then method to If the chain execution continues, 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); }); <html> <head> <title>Ball move</title> <style type="text/css"> .ball { width: 40px; height: 40px; border-radius: 20px; margin-left: 10px; } .ball1 { background: #ff0000; } .ball2 { background: #00ff00; } .ball3 { background: #0000ff; } </style> <script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script> </head> <body> <p class="ball ball1"></p> <p class="ball ball2"></p> <p class="ball ball3"></p> <script type="text/javascript"> 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> </body> </html>
The above is the example code (demo) of using Promise to implement traffic lights in JS introduced by the editor. I hope it will be helpful to everyone! !
Related recommendations:
The specific method of using Promise in jQuery
How to implement a complete Promise
About the simple usage of promise objects
The above is the detailed content of Using Promise in JS to implement traffic light example code (demo). For more information, please follow other related articles on the PHP Chinese website!

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.


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

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Zend Studio 13.0.1
Powerful PHP integrated development environment

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

SublimeText3 Linux new version
SublimeText3 Linux latest version

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