0
点赞
收藏
分享

微信扫一扫

面试题 防抖和节流

年夜雪 2022-04-13 阅读 75

// 是什么?
// 防抖和节流都是性能优化的一种手段。
// 防抖:持续触发不执行,不触发的一段时间后才执行。
// 节流:持续触发也执行,只不过,执行的频率变低了。
// 实现一个?
// 匈牙利命名法的简版
// 类型 + 具体的含义
// const iNum = 8
// const bBar = false
// const aDiv = document.querySelctorAll(‘div’)
// 把鼠标相对于盒子位置放到盒子里面
/* oDiv.onmousemove = function (e) {
let x = e.pageX - this.offsetLeft
let t = e.pageY - this.offsetTop
this.innerHTML = x: ${x}, y: ${t}
}; */

// 防抖一下
/* let timer = null
oDiv.onmousemove = function (e) {
clearTimeout(timer)
timer = setTimeout(() => {
let x = e.pageX - this.offsetLeft
let t = e.pageY - this.offsetTop
this.innerHTML = x: ${x}, y: ${t}
}, 200)
}; /
// 封装一个防抖/节流函数?
/
const debounce = (callback, time) => {
let timer = null
return function (e) {
clearTimeout(timer)
timer = setTimeout(() => {
callback.call(this, e) // window.callback(e)
}, time)
}
} */

/* oDiv.onmousemove = _.debounce(function (e) {
let x = e.pageX - this.offsetLeft
let t = e.pageY - this.offsetTop
this.innerHTML = x: ${x}, y: ${t}
}, 200) */
// 生活中的例子?
// 王者荣耀英雄回城是防抖还是节流
// 打散弹枪,节流

// 应用场景?
// 根据输入的内容请求接口?防抖
// 获取窗口缩放的大小,滚动位置?节流

// 实际开发怎么做?
oDiv.onmousemove = _.throttle(function (e) {
let x = e.pageX - this.offsetLeft
let t = e.pageY - this.offsetTop
this.innerHTML = x: ${x}, y: ${t}
}, 1000)

举报

相关推荐

0 条评论