今日在使用jQuery中animate方法的回调函数时,发现当回调函数内嵌animate方法时,而且将这些放在循环中时会出现:先是外部animate被执行,而后再是内部animate被执行。通过屡次试验以及网上查询,发现js引擎单线程的,异步事件只能排队等候执行,而不能同时执行,而只能先执行同步事件。而animate方法是采用计时器和延时器进行闭包而成的方法,相应的计时器和延时器是异步的,故animate方法也是异步执行的。这样就能够解释了:当程序读到animate方法时,因为其是异步执行的,会被挂起,转而执行,同步事件故在通过多个循环后,多个animate方法就被挂在了时间线上,当循环完成后,则转而执行被挂起的animate方法;而内嵌的animate方法亦如此:当外部animate执行后,在读到内部animate语句时,这些语句又被挂起,因此当外部全部animate方法执行后才继而执行内部被挂起的animate方法。值得注意的是当循环采用死循环时,则animate方法会被一直挂起形成程序出错。所以若是想实现一个对象的屡次运动,则能够将屡次运动的代码按前后顺序书写而不是进行嵌套。javascript
如下是程序代码:html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
<script type="text/javascript" src="jquery-3.2.1.min.js"></script>
<style>
p{width:100px; height:100px; background:green; position:absolute; left:0px; top:0px;}
h1{width:100px; height:100px; background:red; position:absolute; left:200px; top:200px;}
</style>
</head>java
<body>
<input value="123" type="checkbox">
<p>123</p>
<h1></h1>
<input type="button" value="change">jquery
</body>
<script>
$('input').click(function(){
function move(){
$('p').animate({left:'100px'},1000,'swing',function(){
/*console.log(1);
$('p').animate({left:'100px',top:'100px',},1,'swing');
console.log(5);
$('p').animate({top:'0px'},1,'swing');*/
//$('p').hide();
$('p').animate({left:'300px',top:'300px',},1000,'swing');
$('p').animate({left:'200px',top:'200px',},1000,'swing');
console.log(1);
});
$('p').animate({left:'000px'},1000,'swing',function(){
$('p').animate({left:'300px',top:'300px',},1000,'swing');
$('p').animate({left:'200px',top:'200px',},1000,'swing');
/*console.log(1);
$('h1').animate({left:'300px',top:'300px',},1000,'swing');
$('p').animate({left:'100px',top:'100px',},1,'swing');
console.log(5);
$('p').animate({top:'0px'},1,'swing');*/
console.log(2);
});
//$('p').hide();
}
for(var i = 0;i < 4 ;i++){
move();
}
});闭包
</script>
</html>异步