一、HTML部分
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>防抖与节流</title>
</head>
<body>
<input type="button" id="debounce" value="防抖"/>
<input type="button" id="throttle" value="节流"/>
</body>
<script src="index.js"></script>
</html>
二、index.js部分
// 防抖
function fangdou(fn,times = 1000){
let time = null;
return function(){
clearTimeout(time);
time = setTimeout(function(){
fn.apply(this,arguments);
},times);
}
}
function hi(){
console.log('防抖成功!');
}
let fd = document.getElementById('debounce');
fd.addEventListener('click', fangdou(hi));
// 节流
function jieliu(fn, times = 1000){
let run = true;
return function(){
if(!run){
return ;
}
run = false;
setTimeout(function(){
fn.apply(this,arguments);
run = true;
},times)
}
}
function hello(){
console.log('节流成功!')
}
let jl = document.getElementById('throttle');
jl.addEventListener('click', jieliu(hello));