1、前言
日常积累,欢迎指正
2、节流函数
连续操作时操作间隔大于指定时间才会执行一次
- 常见应用:搜索框输入即查询
2.1、ES5 版本 - arguments
/** @desc 使用 arguments */
export function debounce(fn,delay=300){
const timer=null
return function(){
if(timer){
clearTimeout(timer)
}
timer=setTimeout(()=>{
// fn.call(this,arguments)
fn.apply(this,arguments)
},delay)
}
}
2.2、ES6 版本 - 剩余运算符
/** @desc 使用剩余运算符 */
export function debounce(fn,delay=300){
const timer=null
return function(...rest){
if(timer){
clearTimeout(timer)
}
timer=setTimeout(()=>{
// fn.call(this,rest)
fn.applay(this,rest)
timer =null
},delay)
}
}
2.3使用
import debounce from 'debounce'
handleSearch = debounce(() => {
// console.log('debounce');
search();
}, 500)
handleSearch()
3、防抖函数
连续操作时操作指定时间执行一次
- 常见应用:可拖动元素的拖动
3.1、ES5 版本 - arguments
/** @desc 使用 arguments */
export function throttle(fn,time=300){
const timer =null
return function(){
if(timer){
return
}
timer=setTimeout(()=>{
fn.apply(this,arguments)
timer=null
},time)
}
}
3.2、ES6 版本 - 剩余运算符
/** @desc 使用剩余运算符 */
export function throttle(fn,time=300){
const timer =null
return function(...rest){
if(timer){
return
}
timer=setTimeout(()=>{
fn.apply(this,rest)
timer=null
},time)
}
}
3.3、使用
import throttle from 'throttle'
handleDrag = throttle(() => {
// console.log('throttle');
drag();
}, 500)
handleDrag()