1.防抖功能实现(包含取消功能实现)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<input type="text">
<button class="cancel">取消</button>
<script>
/**
* 防抖函数:实现防抖以及取消功能
* @param fn 回调函数
* @param delay 延迟时间
*/
function wqdebounce(fn, delay) {
// 1.用于记录上一次事件触发的timer
let timer = null
// 2.触发事件时执行的函数
const _debounce = function (...args) {
// 2.1如果有再次触发(更多次触发)事件,那么取消上一次的事件
if (timer) clearTimeout(timer)
// 2.2延迟去执行对应的fn函数(传入的回调函数)
timer = setTimeout(() => {
fn.apply(this, args)
timer = null // 执行过函数之后,将timer重新置null
}, delay);
}
// 3.给_debounce绑定一个取消的函数
_debounce.cancel = function () {
if (timer) clearTimeout(timer)
timer = null
}
// 返回一个新的函数
return _debounce
}
// 获取input元素
const inputEl = document.querySelector('input')
// 获取button元素
const cancelBtn = document.querySelector('.cancel')
// 实现防抖
let counter = 1
const debounceFn = wqdebounce(function (event) {
console.log(`发送网络请求${counter++}:`, this, event);
}, 2000)
inputEl.oninput = debounceFn
// 实现取消的功能
cancelBtn.onclick = function () {
debounceFn.cancel()
}
</script>
</body>
</html>
2.节流功能实现
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<input type="text">
<script>
/**
* 节流函数:实现节流功能
* @param fn 回调函数
* @param interval 间隔时间
*/
function wqthrottle(fn, interval) {
// 1.用于记录上一次事件触发的时间
let lastTime = 0
// 2.触发事件时执行的函数
const _throttle = function (...args) {
// 2.1获取当前时间
const nowTime = new Date().getTime()
// 2.2如果当前时间减去上次时间大于间隔时间,执行回调函数
if (nowTime - lastTime > interval) {
fn.apply(this, args)
lastTime = nowTime
}
}
return _throttle
}
// 获取input元素
const inputEl = document.querySelector('input')
// 实现节流
let counter = 1
inputEl.oninput = wqthrottle(function (event) {
console.log(`发送网络请求${counter++}:`, this.value, event);
}, 2000)
</script>
</body>
</html>