最近在学习王红元老师的高级js课程,学到了防抖和节流,想写篇笔记记录下,以防忘记,如有错误,欢迎指正
一先上概念
防抖:函数防抖,就是指触发事件后,在 n 秒后只能执行一次,如果在 n 秒内又触发了事件,则会重新计算函数的执行时间。我们可以理解为坐公交,司机开门等5秒如果有一个上车后准备关门,如果有看到后面有人,司机会继续等待5秒,直到没有人上车为止
节流:限制一个函数在一定时间内只能执行一次,我们可以理解为地铁:在正常情况下地铁到站后不管有多少人上车,在一定时间内就会关门,如果后面人有没有赶上,只能等待下一趟
二上代码
基本代码
``
// body
<input placeholder="search" class="search" type="text">
<button class="cancel" id="cancel">取消</button>
// js
var inputEl = document.querySelector('input')
var counter = 0;
function searchChange(event) {
counter++;
console.log('发送' + counter + '次网络请求', this, event)// 元素对象
}
``
基本防抖
inputEl.oninput = debounce(searchChange, 2000, true)
function debounce(fn,delay){
// 定义初一个定时器来保存定时器
let timer = null;
const _debounce = function(){
// 取消上一次定时器
if(timer) clearTimeout(timer)
timer = setTimeout(()=>{
fn()
},delay)
}
return _debounce
}
进阶防抖-this指向和参数
function debounce(fn,delay){
let timer = null
const _debounce = function(...args){
if(timer) clearTimeout(timer)
timer = setTmeout(()=>{
// 因为箭头函数绑定上一层作用域,所以this可以绑定到
fn.apply(this,args)
},delay)
}
}
进阶防抖-立即执行
function debounce(fn,delay,immediate){
let timer = null;
let inInvoke = false; // 定义一个变量保存立即执行
const _debounce = function(...args){
if(timer) clearTimeout(timer)
if(immediate && isInvoke){
fn.apply(this,args)
isInvoke = true
}else{
timer = setTimeout(()=>{
fn.apply(this,args)
isInvoke = false
},delay)
}
}
return _debounce
}
基本节流-节流很复杂我暂时只能消化基本的,后续如果顿悟了继续更新,this和args和节流是一样的
inputEl.oninput = throttle(searchChange, 2000, true)
function throttle = function(fn,interval){
let lastTime = 0;
const _throttle = function(){
// 获取当前事件触发时间
const nowTime = new Data().getTime()
// 使用当前触发的时间间隔以及上一次开始的时间,计算出剩余多长时间需要去触发函数
const remainTime = interval - (nowTime - lastTime)
if(remainTime <= 0){
fn()
lastTime = nowTime //重新赋值lastTime
}
}
}