宏任务和微任务
异步与同步的区别
- 异步不会堵塞程序的执行
- 同步会堵塞程序的执行
使用异步的场景
定时任务 :seTimeout, setInverval
网络请求:ajax请求,动态<img>加载
事件绑定
事件循环
1. 同步和异步任务分别进入不同的执行“场所”,同步进入主线程,
2. 异步进入Event Table并注册函数。当指定的事情完成时,
3. Event Table会将这个函数移入任务队列(Event Queue)。
4. 主线程内的任务执行完毕为空,就去任务队列(Event Queue)读取对应的函数,
5. 进入主线程执行
面试真题
执行顺序
//请写出输出内容
async function async1() {
console.log('async1 start');
await async2();
console.log('async1 end');
}
async function async2() {
console.log('async2');
}
console.log('script start');
setTimeout(function() {
console.log('setTimeout');
}, 0)
async1();
new Promise(function(resolve) {
console.log('promise1');
resolve();
}).then(function() {
console.log('promise2');
});
console.log('script end');
输出结果为:
// 首先执行同步的 在执行异步
// promise是同步的,但是里的四个api是异步的
// async await 也是同步的 但是会先执行调用的 在执行下面的代码
script start
async1 start
async2
promise1
script end
async1 end
promise2
setTimeout