前端使用異步的場景:前端
//1.setTimeout console.log(100); setTimeout(function(){ console.log(200); },0); console.log(300); //輸出結果100/300/200
//2.一、ajax請求 console.log('start'); $.get('./data1.json',function(data1){ console.log(data1); }); console.log('end'); //輸出結果start/end/data1 //2.二、<img>加載 console.log('start'); var img = document.createElement('img'); img.onload = function(){ console.log('loaded'); } img.src = 'xxx.png'; console.log('end'); //輸出結果start/end/loaded
//3.事件綁定 console.log('start'); document.getElementById('btn1').addEventListener('click',function(){ console.log('clicked'); }); console.log('end'); //輸出結果start/end/clicked
同步異步的區別:ajax
//同步 console.log(100); alert(200);//同步會形成阻塞 console.log(300); //異步 console.log(100); setTimeout(function(){ console.log(200); },1000); console.log(300);