虽然经常使用setInterval定时器方法,但没有注意过它是否是异步或同步的问题,因为以前写的关于setInterval的代码,基本模式是这样的:
setInterval(function(){//do something...},1000);
,所以在这种情况下是观察不到异步和同步的问题的,直到有一次我写了这样的代码:setInterval(function(){//do something...},1000);//do an other thing
。
我发现我的代码并没有如我刚开始预期的那样先执行完setInterval中的代码,最后再do an other thing,而是跳过setInterval后直接do an other thing。hin显然这和我当时刚开始接触ajax后遇到的问题(ajax也是异步的)一样,所以setInterval是异步执行的。
测试代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<button onclick="changeValue();">change</button>
</body>
<script type="text/javascript" src="jquery-3.0.0.min.js"></script>
<script type="text/javascript">
var value = 1;
$(function () {
var temp; //代码A
var interval = setInterval(function () { //代码B
console.log("interval执行,当前value=" + value);
if (value > 1) {
temp = value;
clearInterval(interval); //终止循环
}
}, 200);
console.log("temp=" + temp); //代码C
});
function changeValue() {
value++;
}
</script>
</html>