首先用最简单的方式实现一个动画效果
<!doctype> <html> <head> <title>Promise animation</title> <style type="text/css"> .ball { width: 40px; height: 40px; border-radius: 20px; } .ball1 { background: red; } .ball2 { background: yellow; } .ball3 { background: 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"> //定义三个球 var ball1 = document.querySelector('.ball1') var ball2 = document.querySelector('.ball2') var ball3 = document.querySelector('.ball3') //球,移动距离,回调函数 function animate(ball, distance, cd){ //每13毫秒改变一次圆球的位置,直到到达指定位置 setTimeout(function(){ var marginLeft = parseInt(ball.style.marginLeft,10) //球达到预期位置 if(marginLeft === distance){ cd && cd() }else{ //球在左侧 if(marginLeft < distance){ marginLeft++ }else{ //球在右侧 marginLeft-- } //调整球的位置 ball.style.marginLeft = marginLeft animate(ball, distance, cd) } },13) } //控制动画 animate(ball1, 100,function(){ animate(ball2, 200, function(){ animate(ball3, 150, function(){ animate(ball2, 150, function(){ animate(ball1, 150, function(){ }) }) }) }) }) </script> </body> </html>
使用promise实现相同功能
<!doctype> <html> <head> <title>Promise animation</title> <style type="text/css"> .ball { width: 40px; height: 40px; border-radius: 20px; } .ball1 { background: red; } .ball2 { background: yellow; } .ball3 { background: green; } </style> <script src="./node_modules/bluebird/js/browser/bluebird.js" type="text/javascript"></script> </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"> //定义三个球 var ball1 = document.querySelector('.ball1') var ball2 = document.querySelector('.ball2') var ball3 = document.querySelector('.ball3') var Promise = window.Promise function promiseAnimate(ball, distance){ return new Promise(function(resolve, reject){ //球,移动距离,回调函数 function _animate(){ //每13毫秒改变一次圆球的位置,直到到达指定位置 setTimeout(function(){ var marginLeft = parseInt(ball.style.marginLeft,10) //球达到预期位置 if(marginLeft === distance){ resolve() }else{ //球在左侧 if(marginLeft < distance){ marginLeft++ }else{ //球在右侧 marginLeft-- } //调整球的位置 ball.style.marginLeft = marginLeft + 'px' _animate() } },13) } _animate() }) } promiseAnimate(ball1, 100) .then(function(){ return promiseAnimate(ball2, 200) }) .then(function(){ return promiseAnimate(ball3, 150) }) .then(function(){ return promiseAnimate(ball2, 150) }) .then(function(){ return promiseAnimate(ball1, 150) }) </script> </body> </html>