我用Jquery的deferred对象为什么实现不了异步编程?
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>小球运动+递归函数</title>
<style type="text/css">
.ball{
width: 40px;
height: 40px;
border-radius: 50%;
margin-top: 10px;
}
#ball1{
background: red;
}
#ball2{
background: yellow;
}
#ball3{
background: blue;
}
</style>
</head>
<body>
<div class="ball" id = "ball1" style="margin-left:10px"></div>
<div class="ball" id = "ball2" style="margin-left:10px"></div>
<div class="ball" id = "ball3" style="margin-left:10px"></div>
<script src="http://libs.baidu.com/jquery/1.9.1/jquery.js"></script>
<script type="text/javascript">
window.requestAnimFrame = (function() {
return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame ||
function(element) {
return window.setTimeout(callback, 1000 / 60);
};
})();
var ball1 =document.querySelector("#ball1");
var ball2 =document.querySelector("#ball2");
var ball3 =document.querySelector("#ball3");
function animate (ball,distance) {
var dtd = $.Deferred();
requestAnimFrame(function(){
var marginleft = parseInt(ball.style.marginLeft, 10);
if(marginleft === distance){
dtd.resolve();
}else if(marginleft < distance){
marginleft++;
}else{
marginleft--;
}
ball.style.marginLeft = marginleft + 'px';
animate(ball,distance);
});
return dtd;
}
animate(ball1,100).then(function(){
return animate(ball2,200);
}).then(function(){
return animate(ball3,300);
}).then(function(){
return animate(ball3,150);
}).then(function(){
return animate(ball2,150);
}).then(function(){
return animate(ball1,150);
})
</script>
</body>
</html>