您的位置:首页 > 其它

使用回调和Promise两种方法实现3个小球依次移动

2018-01-14 19:29 573 查看
<!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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: