- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title>Title</title>
- </head>
- <body>
- <div style="margin-left: 0; width: 100px;height: 100px;border-radius: 50%;background: red;" id="ball1"></div>
- <div style="margin-left: 0; width: 100px;height: 100px;border-radius: 50%;background: yellow;" id="ball2"></div>
- <div style="margin-left: 0; width: 100px;height: 100px;border-radius: 50%;background: blue;" id="ball3"></div>
- <script>
- var ball1 = document.getElementById('ball1');
- var ball2 = document.getElementById('ball2');
- var ball3 = document.getElementById('ball3');
- function move(element, target) {
- return new Promise(function (resolve,reject) {
- var left = parseInt(getComputedStyle(element, null)['marginLeft']);
- element.timer = setInterval(function () {
- if (left <target) {
- element.style.marginLeft = ++left + 'px';
- } else {
- clearInterval(element.timer);
- resolve && resolve();
- }
- }, 13)
- })
- }
- move(ball1, 100)
- .then(function () {
- return move(ball2, 100);
- /* 此处 return 的作用:
- (1) 此处有 return, 那么上面的 then 已经被注入到实例中脱离链式, 下面的程序有 return 去阻断, 不能立即执行; 下面的 then 由新暴露出来的 promise 实例调用执行.
- (2) 此处无 return, 那么上面的 then 已经被注入到实例中脱离链式, 下面的程序无 return 去阻断; 下面的 then 被上面的实例直接调用, 立即执行.
- */
- })
- .then(function () {
- return move(ball3, 100);
- })
- </script>
- </body>
- </html>
来源: http://www.qdfuns.com/article/40901/a90ac08c5fb5b8d04b46907e13482919.html