每天写点玩玩
4.22
- 简易debounce/throttle
function debounce (fn, delay) {
let timer = null
return function () {
if (timer) {
clearTimeout(timer)
}
timer = setTimeout(() => {
fn.apply(this, arguments)
}, delay)
}
}
function throttle (fn, interval) {
let lasttime = new Date().getTime()
return function () {
let nowtime = new Date().getTime()
if (nowtime - lasttime >= interval) {
fn.apply(this, arguments)
lasttime = nowtime
}
}
}
const input = document.querySelector('input')
let totalcount = 0
function change (event) {
console.log(`第${++totalcount}次请求`, event)
}
//input.oninput = debounce(change, 1000)
input.oninput = throttle(change, 2000)
- 带有取消功能的debounce
function debounce (fn, delay, immediate = false) {
let timer = null
const _debounce = function () {
if (timer) {
clearTimeout(timer)
}
if (immediate) { //立即执行一次
fn.apply(this, arguments)
immediate = false
} else {
timer = setTimeout(() => {
fn.apply(this, arguments)
isinvoke = true
}, delay)
}
}
_debounce.cancel = function () {
if (timer) {
clearTimeout(timer) //清除计时器
}
}
return _debounce
}
const input = document.querySelector('input')
let totalcount = 0
function change (event) {
console.log(`第${++totalcount}次请求`, event)
}
input.oninput = debounce(change, 1000, immediate = true)
const cancelbutton = document.querySelector('button')
cancelbutton.onclick = function () {
input.oninput.cancel()
}
-
防抖使用场景举例
1 用户在输入框内连续输入一串字符的时候,可以规定在用户输入完之后再执行查询
2 频繁点击按钮,触发某个事件
3 用户缩放浏览器的resize事件
4 监听页面滚动事件 -
节流使用场景举例
1 频繁点击按钮,触发某个事件
2 监听页面滚动事件
3 监听鼠标移动事件
4 游戏中的一些设计等