Home Web Front-end JS Tutorial Detailed explanation of using Promise to implement traffic lights in JS

Detailed explanation of using Promise to implement traffic lights in JS

Jan 05, 2018 pm 01:51 PM
javascript promise traffic light

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:

<ul id="traffic" class="">
 <li id="green"></li>
 <li id="yellow"></li>
 <li id="red"></li>
</ul>
Copy after login

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;}
Copy after login

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()
  })
  })();
Copy after login

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); 
}); 
<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>
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to set the traffic light countdown on the Amap map_Tutorial on setting the traffic light countdown on the Amap map How to set the traffic light countdown on the Amap map_Tutorial on setting the traffic light countdown on the Amap map Apr 01, 2024 pm 05:37 PM

1. Users who want to use the traffic light navigation function of Amap must first update the Amap map to the latest version, and then click Driving on the homepage (as shown in the picture). 2. Then enter the starting point and destination, and click to start navigation (as shown in the picture). 3. Finally, when you are about to pass the traffic light on the map, you can see the countdown display (as shown in the picture).

How to set the traffic light countdown in Amap Navigation How to set the traffic light countdown in Amap Navigation Feb 23, 2024 pm 10:07 PM

Amap can set the traffic light countdown, so how to set this function specifically? Users need to open more settings in Amap and then find the custom navigation function to count seconds while navigating. This traffic light countdown setting method tutorial will tell you how to set it up, come and take a look! Amap usage tutorial: How to set the traffic light countdown in Amap navigation 1. First open the software, enter the navigation, and then click More on the lower right. 2. Click the custom navigation button inside. 3. There is an electronic eye display function below, which can be opened by clicking on it.

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

Keeping your word: The pros and cons of delivering on your promises Keeping your word: The pros and cons of delivering on your promises Feb 18, 2024 pm 08:06 PM

In daily life, we often encounter problems between promises and fulfillment. Whether in a personal relationship or a business transaction, delivering on promises is key to building trust. However, the pros and cons of commitment are often controversial. This article will explore the pros and cons of commitments and give some advice on how to keep your word. The promised benefits are obvious. First, commitment builds trust. When a person keeps his word, he makes others believe that he is a trustworthy person. Trust is the bond established between people, which can make people more

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

See all articles