面試題:
1.? ? 異步和同步的區(qū)別,分別舉個(gè)例子
2.????前端使用異步的場(chǎng)景
知識(shí)點(diǎn):
異步:console.log(100)
? ? ? ? ? ? setTimeOut(function () {
? ? ? ? ? ? ? ? console.log(200)
????????????})
? ? ? ? ? ? console.log(300)? ? ? //? ? 100? ?300? ?200
同步:console.log(100)
????????????alert(200)
????????????console.log(300)? ? ? //? ?alert 點(diǎn)擊確定后? 才繼續(xù)執(zhí)行代碼
總結(jié):以上邊異步的例子,
? ? ? ? ? ? 1.? ? 執(zhí)行第一行,打印100
? ? ? ? ? ? 2.????執(zhí)行setTimeOut后,傳入setTimeOut的函數(shù)會(huì)被暫存起來(lái),不會(huì)立即執(zhí)行(單線程的特點(diǎn),不能同時(shí)干兩件事)
? ? ? ? ? ? 3.? ? 執(zhí)行最后一行打印 300
? ? ? ? ? ? 4.????所有程序執(zhí)行完,處于空閑狀態(tài)時(shí),會(huì)檢查是否有暫存起來(lái)的要執(zhí)行,有的話立即執(zhí)行
前端使用異步的場(chǎng)景:
? ? ? ? ? ? 1.? ? 計(jì)時(shí)任務(wù):setTimeOut? setInterval
? ? ? ? ? ? 2.? ? 網(wǎng)絡(luò)請(qǐng)求:Ajax請(qǐng)求? ?動(dòng)態(tài)img加載
? ? ? ? ? ? 3.? ? 事件綁定