<!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>防抖,节流快速理解</title>
</head>
<style>
.box {
height: 9000px;
}
</style>
<body>
<button class="buttonDebounce">防抖点击</button>
<button class="buttonThrottling">节流点击</button>
<script>
//防抖debounce代码:防抖就是单位时间内如重新触发,重新计时,时间到执行
function debounce(timeout, fn) {
let _time = null
return function() {
let _arg = arguments
clearTimeout(_time)
_time = setTimeout(() => {
fn.apply(this, _arg)
}, timeout)
}
}
// 节流函数:节流就是单位时间内只执行一次,时间内触发不做任何操作,到时间以后更改flag可以重新触发
function throttling(time, fun) {
let flag = false;
return () => {
if (flag) {
return null
}
flag = true
// 先调用,在节流
fun.apply(this, arguments)
setTimeout(() => {
// fun.apply(this,arguments)// 先节流,在调用
flag = false
}, time);
}
}
function handleDebounce() {
console.log("已防抖,请执行操作");
}
function handleThrottling() {
console.log("已节流,请执行操作");
}
document.querySelector('.buttonDebounce').addEventListener('click', debounce(500, handleDebounce))
document.querySelector('.buttonThrottling').addEventListener('click', throttling(1500, handleThrottling))
</script>
</body>
</html>
|