1. Debounce(防抖)
- 定义:
在事件被触发n秒后再执行回调,如果在这n秒内又被触发,则重新计时。
- 应用场景:输入框,不输了再执行函数
- 代码:
const debounce = (fn, wait) => {
return function () {
clearTimeout(fun.id)
fun.id = setTimeout(() => {
fun.call(this, arguments)
}, delay)
}
}
2. Throttle(节流)
- 定义:
规定在一个单位时间内,只能触发一次函数。如果这个单位时间内触发多次函数,只有一次生效。
- 应用场景:监听滚动事件,滑到底部自动加载更多
- 代码:
const throttle1 = (fn, wait) => {
let last = 0
return function () {
let now = Date.now()
if (now - last >= wait) {
last = now
fn.apply(this, arguments)
}
}
}
const throttle2 = (fn, wait) => {
let timer = null
return function () {
if (!timer) {
timer = setTimeout(() => {
fn.apply(this, arguments)
timer = null
}, wait)
}
}
}
const throttle = (func, wait, options) => {
var context, args, result
var timeout = null
var previous = 0
if (!options) options = {}
var later = function() {
previous = options.leading === false ? 0 : Date.now()
timeout = null
result = func.apply(context, args)
if (!timeout) context = args = null
}
return function() {
var now = Date.now()
if (!previous && options.leading === false) previous = now
var remaining = wait - (now - previous)
context = this
args = arguments
if (remaining <= 0 || remaining > wait) {
if (timeout) {
clearTimeout(timeout)
timeout = null
}
previous = now
result = func.apply(context, args)
if (!timeout) context = args = null
} else if (!timeout && options.trailing !== false) {
timeout = setTimeout(later, remaining)
}
return result
}
}
const test = () => {
console.log(Math.random())
}
setInterval(throttle(test, 3000), 100)