JavaScript执行 Javascript引擎和页面渲染引擎在同一个渲染线程,GUI渲染和Javascript执行两者是互斥的
如果某个任务执行时间过长,浏览器会推迟渲染
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>RAF</title>
</head>
<body>
<div style="background: lightblue;width: 0;height: 20px;"></div>
<button>开始</button>
<script>
/**
* requestAnimationFrame(callback) 由浏览器专门为动画提供的API
* cancelAnimationFrame(返回值) 清除动画
* <16.7 丢帧
* >16.7 跳跃 卡顿
*/
const div = document.querySelector('div');
const button = document.querySelector('button');
let start;
function progress() {
div.style.width = div.offsetWidth + 1 + 'px';
div.innerHTML = (div.offsetWidth) + '%';
if (div.offsetWidth < 100) {
let current = Date.now();
console.log(current - start);
start = current;
timer = requestAnimationFrame(progress);
}
}
button.onclick = () => {
div.style.width = 0;
start = Date.now();
requestAnimationFrame(progress);
}
</script>
</body>
</html>
16 ms
,说明时间有富余,此时就会执行 requestIdleCallback
里注册的任务window.requestIdleCallback(
callback: (deaLine: IdleDeadline) => void,
option?: {timeout: number}
)
interface IdleDeadline {
didTimeout: boolean // 表示任务执行是否超过约定时间
timeRemaining(): DOMHighResTimeStamp // 任务可供执行的剩余时间
}
<body>
<script>
function sleep(d) {
for (var t = Date.now(); Date.now() - t <= d;);
}
const works = [
() => {
console.log("第1个任务开始");
sleep(0);//sleep(20);
console.log("第1个任务结束");
},
() => {
console.log("第2个任务开始");
sleep(0);//sleep(20);
console.log("第2个任务结束");
},
() => {
console.log("第3个任务开始");
sleep(0);//sleep(20);
console.log("第3个任务结束");
},
];
requestIdleCallback(workLoop, { timeout: 1000 });
function workLoop(deadline) {
console.log('本帧剩余时间', parseInt(deadline.timeRemaining()));
while ((deadline.timeRemaining() > 1 || deadline.didTimeout) && works.length > 0) {
performUnitOfWork();
}
if (works.length > 0) {
console.log(`只剩下${parseInt(deadline.timeRemaining())}ms,时间片到了等待下次空闲时间的调度`);
requestIdleCallback(workLoop);
}
}
function performUnitOfWork() {
works.shift()();
}
</script>
</body>
requestIdleCallback
目前只有Chrome支持var channel = new MessageChannel();
//channel.port1
//channel.port2
var channel = new MessageChannel();
var port1 = channel.port1;
var port2 = channel.port2;
port1.onmessage = function(event) {
console.log("port1收到来自port2的数据:" + event.data);
}
port2.onmessage = function(event) {
console.log("port2收到来自port1的数据:" + event.data);
}
port1.postMessage("发送给port2");
port2.postMessage("发送给port1");
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
const channel = new MessageChannel()
let pendingCallback;
let startTime;
let timeoutTime;
let perFrameTime = (1000 / 60);
let timeRemaining = () => perFrameTime - (Date.now() - startTime);
channel.port2.onmessage = () => {
if (pendingCallback) {
pendingCallback({ didTimeout: Date.now() > timeoutTime, timeRemaining });
}
}
window.requestIdleCallback = (callback, options) => {
timeoutTime = Date.now() + options.timeout;
requestAnimationFrame(() => {
startTime = Date.now();
pendingCallback = callback;
channel.port1.postMessage('hello');
})
/* startTime = Date.now();
setTimeout(() => {
callback({ didTimeout: Date.now() > timeoutTime, timeRemaining });
}); */
}
function sleep(d) {
for (var t = Date.now(); Date.now() - t <= d;);
}
const works = [
() => {
console.log("第1个任务开始");
sleep(30);//sleep(20);
console.log("第1个任务结束");
},
() => {
console.log("第2个任务开始");
sleep(30);//sleep(20);
console.log("第2个任务结束");
},
() => {
console.log("第3个任务开始");
sleep(30);//sleep(20);
console.log("第3个任务结束");
},
];
requestIdleCallback(workLoop, { timeout: 60 * 1000 });
function workLoop(deadline) {
console.log('本帧剩余时间', parseInt(deadline.timeRemaining()));
while ((deadline.timeRemaining() > 1 || deadline.didTimeout) && works.length > 0) {
performUnitOfWork();
}
if (works.length > 0) {
console.log(`只剩下${parseInt(deadline.timeRemaining())}ms,时间片到了等待下次空闲时间的调度`);
requestIdleCallback(workLoop, { timeout: 60 * 1000 });
}
}
function performUnitOfWork() {
works.shift()();
}
</script>
</body>
</html>
class Update {
constructor(payload) {
this.payload = payload;
this.nextUpdate = null;
}
}
class UpdateQueue {
constructor() {
this.baseState = null;
this.firstUpdate = null;
this.lastUpdate = null;
}
clear() {
this.firstUpdate = null;
this.lastUpdate = null;
}
enqueueUpdate(update) {
if (this.firstUpdate === null) {
this.firstUpdate = this.lastUpdate = update;
} else {
this.lastUpdate.nextUpdate = update;
this.lastUpdate = update;
}
}
forceUpdate() {
let currentState = this.baseState || {};
let currentUpdate = this.firstUpdate;
while (currentUpdate) {
let nexState = typeof currentUpdate.payload == 'function' ? currentUpdate.payload(currentState) : currentUpdate.payload;
currentState = { ...currentState, ...nexState };
currentUpdate = currentUpdate.nextUpdate;
}
this.firstUpdate = this.lastUpdate = null;
this.baseState = currentState;
return currentState;
}
}
let queue = new UpdateQueue();
queue.enqueueUpdate(new Update({ name: 'zhufeng' }));
queue.enqueueUpdate(new Update({ number: 0 }));
queue.enqueueUpdate(new Update(state => ({ number: state.number + 1 })));
queue.enqueueUpdate(new Update(state => ({ number: state.number + 1 })));
queue.forceUpdate();
console.log(queue.baseState);
Reconcilation
期间,React 会一直占用着浏览器资源,一则会导致用户触发的事件得不到响应, 二则会导致掉帧,用户可能会感觉到卡顿let root = {
key: 'A1',
children: [
{
key: 'B1',
children: [
{
key: 'C1',
children: []
},
{
key: 'C2',
children: []
}
]
},
{
key: 'B2',
children: []
}
]
}
function walk(element) {
doWork(element);
element.children.forEach(walk);
}
function doWork(element) {
console.log(element.key);
}
walk(root);
适时
地让出CPU执行权,除了可以让浏览器及时地响应用户的交互Fiber
type Fiber = {
//类型
type: any,
//父节点
return: Fiber,
// 指向第一个子节点
child: Fiber,
// 指向下一个弟弟
sibling: Fiber
}
let A1 = { type: 'div', key: 'A1' };
let B1 = { type: 'div', key: 'B1', return: A1 };
let B2 = { type: 'div', key: 'B2', return: A1 };
let C1 = { type: 'div', key: 'C1', return: B1 };
let C2 = { type: 'div', key: 'C2', return: B1 };
A1.child = B1;
B1.sibling = B2;
B1.child = C1;
C1.sibling = C2;
module.exports = A1;
let rootFiber = require('./element');
//下一个工作单元
let nextUnitOfWork = null;
//render工作循环
function workLoop() {
while (nextUnitOfWork) {
//执行一个任务并返回下一个任务
nextUnitOfWork = performUnitOfWork(nextUnitOfWork);
}
//render阶段结束
}
function performUnitOfWork(fiber) {
beginWork(fiber);
if (fiber.child) {//如果子节点就返回第一个子节点
return fiber.child;
}
while (fiber) {//如果没有子节点说明当前节点已经完成了渲染工作
completeUnitOfWork(fiber);//可以结束此fiber的渲染了
if (fiber.sibling) {//如果它有弟弟就返回弟弟
return fiber.sibling;
}
fiber = fiber.return;//如果没有弟弟让爸爸完成,然后找叔叔
}
}
function beginWork(fiber) {
console.log('beginWork', fiber.key);
//fiber.stateNode = document.createElement(fiber.type);
}
function completeUnitOfWork(fiber) {
console.log('completeUnitOfWork', fiber.key);
}
nextUnitOfWork = rootFiber;
workLoop();
let container = document.getElementById('root');
let C1 = { type: 'div', key: 'C1', props: { id: 'C1', children: [] } };
let C2 = { type: 'div', key: 'C2', props: { id: 'C2', children: [] } };
let B1 = { type: 'div', key: 'B1', props: { id: 'B1', children: [C1, C2] } };
let B2 = { type: 'div', key: 'B2', props: { id: 'B2', children: [] } };
let A1 = { type: 'div', key: 'A1', props: { id: 'A1', children: [B1, B2] } };
let nextUnitOfWork = null;
let workInProgressRoot = null;
function workLoop() {
while (nextUnitOfWork) {
nextUnitOfWork = performUnitOfWork(nextUnitOfWork);
}
if (!nextUnitOfWork) { //render阶段结束
commitRoot();
}
}
function commitRoot() {
let fiber = workInProgressRoot.firstEffect;
while (fiber) {
console.log(fiber.key); //C1 C2 B1 B2 A1
commitWork(fiber);
fiber = fiber.nextEffect;
}
workInProgressRoot = null;
}
function commitWork(currentFiber) {
currentFiber.return.stateNode.appendChild(currentFiber.stateNode);
}
function performUnitOfWork(fiber) {
beginWork(fiber);
if (fiber.child) {
return fiber.child;
}
while (fiber) {
completeUnitOfWork(fiber);
if (fiber.sibling) {
return fiber.sibling;
}
fiber = fiber.return;
}
}
function beginWork(currentFiber) {
if (!currentFiber.stateNode) {
currentFiber.stateNode = document.createElement(currentFiber.type);//创建真实DOM
for (let key in currentFiber.props) {//循环属性赋赋值给真实DOM
if (key !== 'children' && key !== 'key')
currentFiber.stateNode.setAttribute(key, currentFiber.props[key]);
}
}
let previousFiber;
currentFiber.props.children.forEach((child, index) => {
let childFiber = {
tag: 'HOST',
type: child.type,
key: child.key,
props: child.props,
return: currentFiber,
effectTag: 'PLACEMENT',
nextEffect: null
}
if (index === 0) {
currentFiber.child = childFiber;
} else {
previousFiber.sibling = childFiber;
}
previousFiber = childFiber;
});
}
function completeUnitOfWork(currentFiber) {
const returnFiber = currentFiber.return;
if (returnFiber) {
if (!returnFiber.firstEffect) {
returnFiber.firstEffect = currentFiber.firstEffect;
}
if (currentFiber.lastEffect) {
if (returnFiber.lastEffect) {
returnFiber.lastEffect.nextEffect = currentFiber.firstEffect;
}
returnFiber.lastEffect = currentFiber.lastEffect;
}
if (currentFiber.effectTag) {
if (returnFiber.lastEffect) {
returnFiber.lastEffect.nextEffect = currentFiber;
} else {
returnFiber.firstEffect = currentFiber;
}
returnFiber.lastEffect = currentFiber;
}
}
}
console.log(container);
workInProgressRoot = {
key: 'ROOT',
stateNode: container,
props: { children: [A1] }
};
nextUnitOfWork = workInProgressRoot;//从RootFiber开始,到RootFiber结束
workLoop();