index.js
import React from 'react';
import ReactDOM from 'react-dom';
let element = (
<div id="A1">
<div id="B1">
<div id="C1"></div>
<div id="C2"></div>
</div>
<div id="B2"></div>
</div>
)
console.log(JSON.stringify(element,null,2));
ReactDOM.render(element,document.getElementById('root'));
let element = {
"type": "div",
"key": "A1",
"props": {
"id": "A1",
"children": [
{
"type": "div",
"key": "B1",
"props": {
"id": "B1",
"children": [
{
"type": "div",
"key": "C1",
"props": { "id": "C1"},
},
{
"type": "div",
"key": "C2",
"props": {"id": "C2"},
}
]
},
},
{
"type": "div",
"key": "B2",
"props": {"id": "B2"},
}
]
},
}
function render(element, container) {
let dom = document.createElement(element.type);
Object.keys(element.props).filter(key => key !== 'children').forEach(key => {
dom[key] = element.props[key];
});
if(Array.isArray(element.props.children)){
element.props.children.forEach(child=>render(child,dom));
}
container.appendChild(dom);
}
render(element, document.getElementById('root'));
Fiber
架构,让自己的协调过程变成可被中断。 适时地让出CPU执行权,除了可以让浏览器及时地响应用户的交互requestAnimationFrame(callback)
会在浏览器每次重绘前执行 callback 回调, 每次 callback 执行的时机都是浏览器刷新下一帧渲染周期的起点上requestAnimationFrame(callback)
的回调 callback 回调参数 timestamp 是回调被调用的时间,也就是当前帧的起始时间rAfTime performance.timing.navigationStart + performance.now() 约等于 Date.now()
<!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(rAfTime) {
div.style.width = div.offsetWidth + 1 + 'px';
div.innerHTML = (div.offsetWidth) + '%';
if (div.offsetWidth < 100) {
let current = Date.now();
console.log((current - start)+'ms');
start = current;
timer = requestAnimationFrame(progress);
}
}
button.onclick = () => {
div.style.width = 0;
start = Date.now();
requestAnimationFrame(progress);
}
</script>
</body>
</html>
requestAnimationFrame
的回调会在每一帧确定执行,属于高优先级任务,而requestIdleCallback
的回调则不一定,属于低优先级任务window.requestIdleCallback(
callback: (deaLine: IdleDeadline) => void,
option?: {timeout: number}
)
interface IdleDeadline {
didTimeout: boolean // 表示任务执行是否超过约定时间
timeRemaining(): DOMHighResTimeStamp // 任务可供执行的剩余时间
}
<body>
<script>
function sleep(duration) {
let start =Date.now();
while(start+duration>Date.now()){}
}
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>
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;//等待执行的callback
let activeFrameTime = (1000 / 60);//在每秒60帧的情况下每帧的时间
//当前帧的剩余时间是frameDeadline减去当前时间的差值来判断
let timeRemaining = () => frameDeadline - performance.now();
channel.port2.onmessage = () => {
var currentTime = performance.now();
var didTimeout = frameDeadline <= currentTime;
if(didTimeout || timeRemaining()>1){
if (pendingCallback) {
pendingCallback({ didTimeout: frameDeadline <= currentTime, timeRemaining });
}
}
}
window.requestIdleCallback = (callback, options) => {
requestAnimationFrame((rafTime) => {//当前动画帧开始的时间
frameDeadline = rafTime + activeFrameTime;
pendingCallback = callback;
//把任务推入event loop的task queue中等待执行
channel.port1.postMessage('hello');
})
}
function sleep(d) {
for (var t = Date.now(); Date.now() - t <= d;);
}
const works = [
() => {
console.log("第1个任务开始");
sleep(20);//sleep(20);
console.log("第1个任务结束");
},
() => {
console.log("第2个任务开始");
sleep(20);//sleep(20);
console.log("第2个任务结束");
},
() => {
console.log("第3个任务开始");
sleep(0);//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: 2 * 1000 });
}
}
function performUnitOfWork() {
works.shift()();
}
</script>
</body>
</html>
没有父节点遍历结束
先儿子,后弟弟,再叔叔,辈份越小越优先
let A1 = { type: 'div', props:{id: 'A1'} };
let B1 = { type: 'div', props:{id: 'B1'}, return: A1 };
let B2 = { type: 'div', props:{id: 'B2'}, return: A1 };
let C1 = { type: 'div', props:{id: 'C1'}, return: B1 };
let C2 = { type: 'div', props:{id: 'C2'}, return: B1 };
A1.child = B1;
B1.sibling = B2;
B1.child = C1;
C1.sibling = C2;
//下一个工作单元
let nextUnitOfWork = null;
//render工作循环
function workLoop() {
while (nextUnitOfWork) {
//执行一个任务并返回下一个任务
nextUnitOfWork = performUnitOfWork(nextUnitOfWork);
}
console.log('render阶段结束');
//render阶段结束
}
function performUnitOfWork(fiber) {
let child = beginWork(fiber);
if(child){
return child;
}
while (fiber) {//如果没有子节点说明当前节点已经完成了渲染工作
completeUnitOfWork(fiber);//可以结束此fiber的渲染了
if (fiber.sibling) {//如果它有弟弟就返回弟弟
return fiber.sibling;
}
fiber = fiber.return;//如果没有弟弟让爸爸完成,然后找叔叔
}
}
function beginWork(fiber) {
console.log('beginWork', fiber.props.id);
return fiber.child;
}
function completeUnitOfWork(fiber) {
console.log('completeUnitOfWork', fiber.props.id);
}
nextUnitOfWork = A1;
workLoop();
let container = document.getElementById('root');
let C1 = { type: 'div', props: { id: 'C1', children: [] } };
let C2 = { type: 'div', props: { id: 'C2', children: [] } };
let B1 = { type: 'div', props: { id: 'B1', children: [C1, C2] } };
let B2 = { type: 'div', props: { id: 'B2', children: [] } };
let A1 = { type: 'div', 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.props.id); //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[key]=currentFiber.props[key];
}
}
let previousFiber;
currentFiber.props.children.forEach((child, index) => {
let childFiber = {
type: child.type,
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;
}
}
}
workInProgressRoot = {
key: 'ROOT',
stateNode: container,
props: { children: [A1] }
};
nextUnitOfWork = workInProgressRoot;//从RootFiber开始,到RootFiber结束
workLoop();