节流和防抖
1、节流(throttle)
规定一个单位时间,在这个单位时间内,只能有一次触发事件的回调函数执行,如果在同一个单位时间内某事件被触发多次,只有一次能生效。
代码就是这样的:
let _lastTime = null;
// 节流函数,规定时间内只触发一次
function throttle(fn, gapTime) {
return (args) => {
let _nowTime = +new Date();
if (_nowTime - _lastTime > gapTime || !_lastTime) {
fn(args);
_lastTime = _nowTime
}
}
}
2、防抖(debounce)
在事件被触发n秒后再执行回调,如果在这n秒内又被触发,则重新计时。
代码是这样的:
// 防抖函数
let timeout = null;
// 防抖函数,延迟一段时间后执行函数,如果时间内又触发了那么从新计时
function debounce(fn, wait) {
return (args) => {
if (timeout !== null) {
clearTimeout(timeout)
}
timeout = setTimeout(() => fn(args), wait)
}
}
节流和防抖我放到一起了,大家可以体验一下两者区别
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<button id="click">防抖</button>
<button id="click1">节流</button>
<body>
<script>
// 防抖函数
let timeout = null;
// 防抖函数,延迟一段时间后执行函数,如果时间内又触发了那么从新计时
function debounce(fn, wait) {
return (args) => {
if (timeout !== null) {
clearTimeout(timeout)
}
timeout = setTimeout(() => fn(args), wait)
}
}
function handle(args) {
console.log(args)
console.log('处理函数防抖', parseInt((Math.random() * 100)))
}
// 节流
let _lastTime = null;
// 节流函数,规定时间内只触发一次
function throttle(fn, gapTime) {
return (args) => {
let _nowTime = +new Date();
if (_nowTime - _lastTime > gapTime || !_lastTime) {
fn(args);
_lastTime = _nowTime
}
}
}
function handle1(args) {
console.log(args)
console.log('处理函数节流', parseInt((Math.random() * 100)))
}
const btn = document.querySelector("#click")
const btn1 = document.querySelector("#click1")
btn.addEventListener('click', () => {
debounce(handle, 1000)({
id: 'name'
});
})
btn1.addEventListener('click', () => {
throttle(handle1, 1500)({
1: 2
});
})
</script>
</body>
</html>