如下面代码,想要它按照调用执行顺序来输出1,2
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<script>
var adopt=false
function a1(){
setTimeout(function(){
console.log(1)
},1000)
}
function a2(){
console.log(2)
}
function a3(){
a1()
a2()
}
a3()
</script>
</body>
</html>
但结果输出是2,1有时是1,2
很显然方法异步执行了,要改成异步可以用一个状态量来限制
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <script> var adopt = false function a1() { console.log(1) adopt = true return adopt } function a2() { console.log(2) } function a3() { a1() if (!adopt) { return } a2() } a3() </script> </body> </html>
这样就是每次输出都是1,2
这是我的片面测试,我对这个方法也不是十分确信,如果有发现错误或bug欢迎留言指正,谢谢!