说明:可直接cv代码到控制台 F12 运行
一、Promise.all 多接口请求,所有请求完成后打印所有请求结果
const url = [100, 200, 300, 400, 500, 600, 700, 800, 900, 2000]
function request(u) {
return new Promise(resolve => {
setTimeout(() => {
if (u === 500 || u === 700) {
resolve('error')
} else {
resolve(u)
}
}, u)
})
}
async function allRequest(urls) {
const res = await Promise.all(urls.map(u => {
return request(u)
}))
const newRes = res.filter(r => r !== 'error')
console.log(res)
console.log(newRes)
}
allRequest(url)
二、递归节点查找
const treeData = [
{
name: "节点1",
children: [
{
name: "节点1-1",
children: [],
},
{
name: "节点1-2",
children: [
{
name: "节点1-2-1",
children: [],
},
],
},
],
},
{
name: "节点2",
children: [
{
name: "节点2-1",
children: [],
},
],
},
];
function fn(arr, name, callback) {
arr.forEach(v => {
if (v.name === name) callback(v)
if (v.children) fn(v.children, name, callback)
})
}
fn(treeData, '节点1-2-1', res => {
console.log(res)
})
三、渲染性能代码优化
1、代码优化
const demo = document.createElement('div')
demo.setAttribute('id', 'demo')
document.body.append(demo)
const el = document.querySelector('#demo');
for (let i = 0; i < 1000; i++) {
el .innerHTML += `<option value="${i}">第${i}个选项</option>`;
}
const el = document.querySelector('#demo');
let htmls = ''
for (let i = 0; i < 1000; i++) {
htmls += `<option value="${i}">第${i}个选项</option>`;
}
el.innerHTML = htmls
2、再次优化,防抖?懒加载??
const demo = document.createElement('div')
demo.setAttribute('id', 'demo')
document.body.append(demo)
let htmls = ''
let oldEl = ''
const el = document.querySelector('#demo');
function fd(callback, delay) {
let time = null
return () => {
clearTimeout(time)
time = setTimeout(callback, delay)
}
}
function lazy(callback, oldEl, noDataLength = 150) {
if (oldEl.length >= noDataLength) {
if (!document.getElementById('no-data')) {
const div = document.createElement('div')
div.setAttribute('id', 'no-data')
div.innerText = '没有更多数据了...'
el.appendChild(div)
}
return false
}
const st = document.documentElement.scrollTop
const cH = document.documentElement.clientHeight
const sH = document.body.scrollHeight
if (st + cH > sH) callback()
}
window.addEventListener('load', () => {
for (let i = 0; i < 50; i++) {
htmls += `<option value="${i}">第${i}个选项</option>`;
}
el.innerHTML = htmls
})
window.addEventListener('scroll', fd(() => {
lazy(() => {
oldEl = document.querySelectorAll('#demo option');
for (let i = 0; i < 50; i++) {
let option = document.createElement('option')
option.setAttribute('value', oldEl.length + i)
option.innerText = `第${oldEl.length + i}个选项`
el.appendChild(option)
}
}, oldEl, 100)
}, 500))
|