<!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>
使用回调和Promise两种方法实现3个小球依次移动
最新推荐文章于 2022-03-02 11:48:03 发布