使用回調和Promise兩種方法實現3個小球依次移動

<!DOCTYPE html>
<html>
<head>
	<title>promise調用</title>
	<style type="text/css">
		.ball{
			width: 20px;
			height: 20px;
			border-radius: 50%;
		}
		.ball1{
			background-color: red;
		}
		.ball2{
			background-color: yellow;
		}
		.ball3{
			background-color: green;
		}
	</style>
</head>
<body>
	<div class="ball ball1" style="margin-left: 0"></div>
	<div class="ball ball2" style="margin-left: 0"></div>
	<div class="ball ball3" style="margin-left: 0"></div>
	<script type="text/javascript">
		let ball1 = document.querySelector(".ball1");
		let ball2 = document.querySelector(".ball2");
		let ball3 = document.querySelector(".ball3");
		//原生回調方法
		function animate(ball,distance,cb){
			setTimeout(function(){
				let marginLeft = parseInt(ball.style.marginLeft,10);
				if(marginLeft === distance){
					cb&&cb()
					return;
				}else{
					if(marginLeft < distance){
						marginLeft++;
					}else{
						marginLeft--;
						// debugger;
					}
				}
				ball.style.marginLeft = marginLeft + 'px';
				animate(ball,distance,cb)
			},13)
		}
		animate(ball1,100,function(){
			animate(ball2,200,function(){
				animate(ball3,300,function(){
					animate(ball3,150,function(){
						animate(ball2, 150,function(){
							animate(ball1,150,function(){

							})
						})
					})
				})
			})
		})

		//promise 方法
		function promiseAinmate(ball,distance) {
			return new Promise(function(resolve,reject) {
						function _animate(){
						setTimeout(function(){
						let marginLeft = parseInt(ball.style.marginLeft,10);
						if(marginLeft === distance){
							resolve()
							return;
						}else{
							if(marginLeft < distance){
								marginLeft++;
							}else{
								marginLeft--;
								// debugger;
							}
						}
						ball.style.marginLeft = marginLeft + 'px';
						_animate();
					},13)
				}
				_animate();
			})
		}
		promiseAinmate(ball1,100)
		.then(function(){
			return promiseAinmate(ball2,200)
		})
		.then(function(){
			return promiseAinmate(ball3,300)
		})
		.then(function(){
			return promiseAinmate(ball3,150)
		})
		.then(function(){
			return promiseAinmate(ball2,150)
		})
		.then(function(){
			return promiseAinmate(ball1,150)
		})

	</script>
</body>
</html>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章