防抖
定义
频繁操作防止抖动,在操作n秒内不操作,才触发事件,若继续操作,则重新计时
使用场景
- 输入框输入
- 缩放resize
代码
function debounce(func, delay = 300, immediate = false) {
let timer = null
return function() {
if (timer) {
clearTimeout(timer)
}
if (immediate && !timer) {
func.apply(this, arguments)
}
timer = setTimeout(() => {
func.apply(this, arguments)
}, delay)
}
}
在vue中使用
写在公共方法utils里引入
import { debounce } from 'utils'
methods: {
appSearch:debounce(function(e.target.value){
this.handleSearch(value)
}, 1000),
handleSearch(value) {
console.log(value)
}
}
节流
定义
频繁操作稀释函数执行,频繁操作时,每隔n秒才触发一次
使用场景
- 鼠标点击,mousedown mousemove单位时间只执行一次
- 滚动事件,懒加载、滚动加载、加载更多或监听滚动条位置
- 防止高频点击提交,防止表单重复提交
代码
function throttle (func, delay = 300) {
let prev = 0
return function() {
let now = Date.now()
if ((now - prev) >= delay) {
func.apply(this, arguments)
prev = Date.now()
}
}
}
总结
- 函数防抖和函数节流都是防止某一时间频繁触发,但是这两兄弟之间的原理却不一样
- 函数防抖是某一段时间内只执行一次,而函数节流是间隔时间执行
结合应用场景
- debounce
- search搜索联想,用户在不断输入时,用防抖来节约请求资源
- window触发resize的时候,不断的调整浏览器窗口大小会不断的触发这个事件,用防抖来让其只触发一次
- throttle
- 鼠标不断点击触发(表单提交),mousedown(单位之间内只触发一次)
- 监听滚动事件,比如是否滑动到底部自动加载更多,用throttle来判断