防抖: 指触发事件后在 n 秒内函数只能执行一次,如果在 n 秒内又触发了事件,则会重新计算函数执行时间。
使用场景:
1、搜索框搜索,只执行最后一次
2、滚动条滚动等事件,完成后执行一次
/*
* 防抖-简易版
* @param func { function } 回调函数
* @param wait { number } 毫秒数
*/
function debounce(func, wait) {
let timeout
return function() {
const context = this
const args = arguments
if (timeout) {
clearTimeout(timeout)
}
timeout = setTimeout(() => {
func.apply(context, args)
}, wait)
}
}
/**
* 防抖-立即执行版 * @param func { function } 回调函数
* @param wait { number } 毫秒数
* @param immediate { boolean } 是否先执行一次
*/
function debounce(func, wait, immediate) {
let timeout
return function() {
const context = this
const args = arguments
if (timeout) {
clearTimeout(timeout)
}
if (immediate) {
const callNow = !timeout
timeout = setTimeout(() => {
timeout = null
}, wait)
// 第一次timeout为undefined,先执行函数
if (callNow) {
func.apply(context, args)
}
} else {
timeout = setTimeout(() => {
func.apply(context, args)
}, wait)
}
}
}
/**
* 防抖-立即执行-返回值 * @param func { function } 回调函数
* @param wait { number } 毫秒数
* @param immediate { boolean } 是否先执行一次
*/
function debounce(func, wait, immediate) {
let timeout, result
return function() {
const context = this
const args = arguments
if (timeout) {
clearTimeout(timeout)
}
if (immediate) {
const callNow = !timeout
timeout = setTimeout(() => {
timeout = null
}, wait)
// 第一次timeout为undefined,先执行函数
if (callNow) {
func.apply(context, args)
}
} else {
timeout = setTimeout(() => {
result = func.apply(context, args)
}, wait)
}
return result
}
}
节流: 指连续触发事件但是在 n 秒中只执行一次函数。
使用场景:
1、上拉加载和下拉刷新,或者鼠标移动等事件
/**
* 节流 * @param func { function } 回调函数
* @param wait { number } 毫秒数
*/
function throttle(func, wait) {
let previous = 0
return function () {
let now = Date.now()
const context = this
const args = arguments
if (now - previous > wait) {
func.apply(context, args)
previous = now
}
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。