requestAnimationFrame 的执行时机是在浏览器的每一帧重绘之前执行。具体来说,它是在微任务执行完毕之后,浏览器进行重绘之前执行的。因此,它的执行顺序如下:
-
执行所有同步任务。
-
执行所有微任务。
-
执行 requestAnimationFrame 回调。
-
浏览器进行重绘。
-
执行所有宏任务。
requestAnimationFrame(() => {
console.log('requestAnimationFrame 1');
setTimeout(() => {
console.log('setTimeout 1');
}, 0);
Promise.resolve().then(() => {
console.log('Promise 1');
});
});
requestAnimationFrame(() => {
console.log('requestAnimationFrame 2');
Promise.resolve().then(() => {
console.log('Promise 2');
});
});
setTimeout(() => {
console.log('setTimeout 2');
}, 0);
Promise.resolve().then(() => {
console.log('Promise 3');
});
Promise 3
requestAnimationFrame 1
Promise 1
requestAnimationFrame 2
Promise 2
setTimeout 2
setTimeout 1
requestAnimationFrame 是一种特殊的任务,它的执行时机介于微任务和宏任务之间。虽然它不完全属于传统意义上的宏任务,但在执行顺序上,它更接近于宏任务