为何两帧间的长间隔不会触发long task?
长帧间隔与Long Task的观测差异问题
我们可以通过递归调用requestAnimationFrame测量浏览器两帧的间隔,在慢加载页面中,部分帧间隔会超过50ms + 帧率——其中50ms是Long Task的最短时长标准(参考MDN中PerformanceLongTaskTiming的定义)。
但将PerformanceLongTaskEntries观测到的Chrome真实Long Task,和递归requestAnimationFrame记录的执行间隔对比时,会发现二者并不一致。
对比脚本
const performanceApiLongTasks = []; const recursiveRAFIntervals = []; function recursiveRAF(callback) { let abort = false; let fn; fn = () => { requestAnimationFrame(() => { if (!abort) { callback(); requestAnimationFrame(fn); } }); } fn(); return () => { abort = true; }; } let prevFrameTime = performance.now(); const stopRaf = recursiveRAF(() => { const startTime = performance.now(); recursiveRAFIntervals.push({ startTime, duration: startTime - prevFrameTime, }); prevFrameTime = startTime; }); const observer = new PerformanceObserver(list => { list.getEntriesByType('longtask').forEach(entry => { performanceApiLongTasks.push(entry); }); }); observer.observe({type: 'longtask', buffered: true}); setTimeout(() => { stopRaf(); observer.disconnect(); compare(); }, 10_000); function compare() { const frameRate = Math.min(...recursiveRAFIntervals.map(({duration}) => duration)); console.log({ performanceApiLongTasks, recursiveRAFIntervals, rafIntervals: recursiveRAFIntervals.filter(({duration}) => duration > 50 + frameRate), frameRate, }); }
运行结果

两种方法得到的时长和条目数量均不相同,现提出技术疑问:为何两帧之间的长间隔不会产生Long Task?
内容的提问来源于stack exchange,提问作者avdotion
相关产品推荐
相关产品推荐

