11.28 笔试
🏠:华龙科技(常州)
总述
知识点
考点 1:这个是吟唱内容,就不多说了
考点 2:
节流:n 秒内执行一次,即使在 n 秒内多次触发,也只会执行一次,n 秒一次,技能冷却
应用场景:加载更多(滚动条),输入框进行远程搜索,快速点击,抢购
实现思路:技能冷却
防抖:如果在 n 秒内再次触发,那么就会重新计时,重新开始
应用场景:窗口改变大小,文本编辑器实时报错
实现思路:重新开始+定时器
代码
javascript
// 实现思路,记住定时器,n秒内只会执行一次
function throttle(func,delay){
const timerId = null
return function(){
let context = this
if(timerId !== null){ // 还在规定时间内
return
}
timerId = setTimeout(function(){
func.call(context)
timerId = null // 执行完成,将timmerId赋值为空
},delay}
}
javascript
// 实现思路:在这一段时间里面只会执行一次
function throttle(func,delay){
const lastTime = 0
return function(){
let context = this
let curTime = Date.now()
if(curTime - lastTine > delay){
func.call(context)
lastTime = curTime
}
}
}
防抖
javascript
// 实现思路:重新开始
function debounce(func,delay){
let timerId = null
return function(){
let context = this
clearTimeout(timerId) // 清除定时器
timerId = setTimeout(function(){ // 重新计时
func.call(context)// 改变this指向
},delay)
}
}
难点 1: 必须使用闭包,函数里面里面嵌套函数,否则一上来,这个函数就会被调用
难点 2:清除延时必须在设置定时器的前面,所以timerId
的设置必须在clearTimeOut
的前面
难点 3:timerId
不可以设置在子函数
内,应该设置在父函数
内
解释:如果放在内部,那么都会执行,定义变量,清除,重新赋值的过程。timerId
就是独立的,互不干涉。
难点 4:调用以后,子函数的运行环境就会变为window
,但是之前的this
,其实指向的是点击的元素
参考文档:
JavaScript 节流 - Web前端工程师面试题讲解_哔哩哔哩_bilibiliJavaScript 节流 - Web前端工程师面试题讲解_哔哩哔哩_bilibili
考点 3:深浅拷贝(后续补上手写方法)
考点 4:参考文档:【前端八股文】事件循环-eventloop_哔哩哔哩_bilibili
考点 5:this指向问题