js防抖和节流区别和实现
防抖【debounce】
当持续触发事件的时候,函数是完全不执行的,等最后一次触发结束的一段时间之后,再去执行。
使用场景【输入实时查询
、多次点击按钮
】
- 持续触发不执行
- 不触发的一段时间之后再执行
节流【throttle】
节流的意思是让函数有节制地执行,而不是毫无节制的触发一次就执行一次。什么叫有节制呢?就是在一段时间内,只执行一次。
使用场景【监听鼠标滚动
,下拉加载数据
】
- 持续触发并不会执行多次
- 到一定时间再去执行
防抖演示:
(频繁调用,只执行最后一次)
节流演示:
(频繁调用,每隔一段时间执行一次)
代码演示
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>防抖节流</title>
<style>
html,
body{
height: 100%;
}
#throttle,#debounce {
height: 200px;
width: 600px;
border: 1px solid #eeeeee;
}
</style>
</head>
<body>
<div id="throttle"></div>
<div id="debounce"></div>
<script>
// ====== 节流
const throttleBox = document.getElementById('throttle')
function throttle(func, delay) {
let run = true
return function () {
if (!run) {
return // 如果开关关闭了,那就直接不执行下边的代码
}
run = false // 持续触发的话,run一直是false,就会停在上边的判断那里,定时器里面函数执行完毕,会重置状态
setTimeout(() => {
func.apply(this, arguments)
run = true // 定时器到时间之后,会把开关打开,我们的函数就会被执行
}, delay)
}
}
// 用法
throttleBox.onmousemove = throttle(function (e) {
throttleBox.innerHTML = `节流==${e.clientX}, ${e.clientY}`
}, 1000)
// ====== 防抖 ======
const debounceBox = document.getElementById('debounce')
function debounce(func, delay) {
let timeout
return function () {
clearTimeout(timeout) // 如果持续触发,那么就清除定时器,定时器的回调就不会执行。
timeout = setTimeout(() => {
func.apply(this, arguments)
}, delay)
}
}
// 用法
debounceBox.onmousemove = debounce(function (e) {
debounceBox.innerHTML = `防抖==${e.clientX}, ${e.clientY}`
}, 1000)
</script>
</body>
</html>
封装防抖方法
export function debounce(func, wait = 1000, immediate = true) {
let timeout
let result
return function(...args) {
const context = this
if (timeout) window.clearTimeout(timeout)
if (immediate) {
const callNow = !timeout
timeout = setTimeout(() => {
timeout = false
}, wait)
if (callNow) result = func.apply(context, args)
} else {
timeout = setTimeout(() => {
func.apply(context, args)
}, wait)
}
return result
}
}