原生JS——Promise实现简单的红绿灯效果

Promise是ES6中新增的构造函数

Promise表示一个异步操作的最终状态(完成或失败),以及其返回的值。

——————————直接上代码————————————

<!doctype html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<style type="text/css">
	body{
		background-color: #ccc;	
	}
		div{
			width: 100px;
			height: 100px;
			border: 1px solid black;
			border-radius: 50%;
		}
		#redLight{
			color: black;
			text-align: center;
			font-size: 35px;
			line-height: 100px;
		}
		#greenLight{
			color: black;
			text-align: center;
			font-size: 35px;
			line-height: 100px;
		}
		#yellowLight{
			color: black;
			text-align: center;
			font-size: 35px;
			line-height: 100px;
		}
	</style>
</head>
<body>
	<div id="redLight">3</div>
	<div id="greenLight"></div>
	<div id="yellowLight"></div>
</body>
</html>
<script type="text/javascript" src="js/packageFunction.js"></script>
<script type="text/javascript">	
// 创建三个灯的对象
function red(){
	// 定时
	let count = 3;
	$("redLight").innerHTML=count;
	$("redLight").style.backgroundColor = "red";
	return new Promise(function(resolve,reject){
		// 每一个灯创建一个定时器
	let timer = setInterval(function(){
		// 灯的颜色改变
		$("redLight").style.backgroundColor = "red";
		count--;
		$("redLight").innerHTML = count;
		if(count<=0){
			count=0;
			clearInterval(timer);
			$("redLight").style.backgroundColor = "#ccc";
			$("redLight").innerHTML="";
			resolve();
		}
	},1000)	
	});
}
function green(){
	let count = 3;
	$("greenLight").innerHTML=count;
	$("greenLight").style.backgroundColor = "green";
	return new Promise(function(resolve,reject){
	let timer = setInterval(function(){
		count--;
		$("greenLight").innerHTML = count;
		if(count<=0){
			count=0;
			clearInterval(timer);
			$("greenLight").style.backgroundColor = "#ccc";
			$("greenLight").innerHTML="";
			resolve();
		}
	},1000)	
	});
	
}
function yellow(){
	let count = 3;
	$("yellowLight").innerHTML=count;
	$("yellowLight").style.backgroundColor = "yellow";
	let n = new Promise(function(resolve,reject){
	let timer = setInterval(function(){
			count--;
			$("yellowLight").innerHTML = count;
			if(count<=0){
				count=0;
				clearInterval(timer);
				$("yellowLight").style.backgroundColor = "#ccc";
				$("yellowLight").innerHTML="";
				resolve();
			}
		},1000)
	});
	return n;
}
function shine(){
	// ES6新写法,避免了构造地狱
	red().then(green).then(yellow).then(shine);
}
window.onload = function(){
	shine();
}
</script>

小弟欢迎大家进行各种批评、指导。
没有封装过程看的更加的直白。

猜你喜欢

转载自blog.csdn.net/weixin_44201257/article/details/86569629