同步执行: 主线程的任务按顺序执行,前一个任务执行完毕,才会执行下一个。简单来说,就是任务不同时执行。
异步执行: 任务处于等待状态,收到主线程的通知时才会执行。简单来说,就是任务同时执行,等待也是执行任务的一种。
1.jQuery中animate()与animate()之间是同步执行
css 部分:
.box{width: 100px;height: 100px;background-color: red;position: absolute;}
html 部分:
<input type="button" class="btn" value="点击" />
<div class="box"></div>
js 部分:
$(".btn").click(function(){
$(".box").animate({
left:400
},2000).animate({
top:400
},2000).animate({
left:0
},2000).animate({
top:20
});
});
2.jQuery中animate()与css()之间是异步执行
css 部分:
.box{width: 100px;height: 100px;background-color: red;position: absolute;}
html 部分:
<input type="button" class="btn" value="点击" />
<div class="box"></div>
js 部分:
$(".btn").click(function(){
$(".box").animate({
left:400
},2000).animate({
top:400
},2000).css({
backgroundColor:"yellow"
});
});
3.如何处理jQuery中animate()与css()之间的异步执行
相同元素处理异步的方法:
css 部分:
.box{width: 100px;height: 100px;background-color: red;position: absolute;}
html 部分:
<input type="button" class="btn1" value="回调函数处理异步" />
<input type="button" class="btn2" value="queue()处理异步" />
<div class="box"></div>
1.利用回调函数处理异步
js 部分:
$(".btn1").click(function(){
$(".box").animate({
left:400
},2000).animate({
top:400
},2000,function(){
$(".box").css({
backgroundColor:"yellow"
});
}).animate({
left:0
},2000);
});
2.利用queue()方法处理异步
js 部分:
$(".btn2").click(function(){
$(".box").animate({
left:400
},2000).animate({
top:400
},2000).queue(function(next){
$(".box").css({
backgroundColor:"yellow"
});
next();
}).animate({
left:0
},2000);
});
不同元素处理异步的方法:
css 部分:
.box1{width: 100px;height: 100px;background-color: red;position: absolute;}
.box2{width: 100px;height: 100px;background-color: blue;position: absolute;top: 150px;}
html 部分:
<input type="button" class="btn1" value="回调地狱处理异步" />
<input type="button" class="btn2" value="Promise封装函数处理异步" />
<div class="box1"></div>
<div class="box2"></div>
1.利用回调地狱处理异步
js 部分:
$(".btn1").click(function(){
$(".box1").animate({
left:500
},1000,function(){
$(".box2").animate({
left:400
},1000,function(){
$(".box1").animate({
top:450
},1000,function(){
$(".box2").animate({
top:350
},1000)
})
})
})
});
2.利用Promise封装函数处理异步
js 部分:
//封装函数
function move(ele,tar,time){
time = time || 1000;
return new Promise((reslove)=>{
ele.animate(tar,time,()=>{
reslove();
})
});
}
//调用
$(".btn2").click(function(){
move($(".box1"),{
left:500
}).then(()=>{
return move($(".box2"),{
left:400
})
}).then(()=>{
return move($(".box1"),{
top:450
})
}).then(()=>{
return move($(".box2"),{
top:350
})
})
});