防抖
解释
: 事件触发之后n秒之后才会执行回调函数, 如果在这个n秒之内再次触发这个事件 , 则重新计时
应用
: 可以用在一些用户点击事件上面 , 避免用户多次点击而向后端发送多次请求
function debounce(fn , wait , args){
let timer = null
return ()=>{
if(timer){
clearTimeout(timer)
timer = null
}
timer = setTimeout(() => {
let newargs = [...arguments].slice(2)
fn.apply(this,newargs)
}, wait);
}
}
节流
解释
: 在一定时间内 , 这个函数只能被触发一次 , 如果在同一时间内这个函数被多次触发 , 只会有一次生效
应用
: 在一些滚动事件上面使用节流 , 可以降低事件触发的频率
function throttle(fn , delay){
let curTime = Date.now()
return ()=>{
let nowTime = Date.now()
if(nowTime-curTime >= delay){
//重新赋值
curTime = Date.now()
fn.apply(this,[...arguments].slice(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>
<style>
button {
position: fixed;
bottom: 50px;
left: 50%;
}
</style>
</head>
<body>
<ul>
<li>12</li>
</ul>
<button>点击添加</button>
<script>
let btn = document.getElementsByTagName('button')[0]
btn.addEventListener('click', throttle(add, 2000, 'lnl'))
function debounce(fn , wait , args){
let timer = null
//箭头函数可以获取外层作用域的this , arguments
return ()=>{
if(timer){
clearTimeout(timer)
timer = null
}
timer = setTimeout(() => {
let newargs = [...arguments].slice(2)
fn.apply(this,newargs)
}, wait);
}
}
function throttle(fn , delay){
let curTime = Date.now()
return ()=>{
let nowTime = Date.now()
if(nowTime-curTime >= delay){
//重新赋值
curTime = Date.now()
fn.apply(this,[...arguments].slice(2))
}
}
}
function add(value) {
let ul = document.getElementsByTagName('ul')[0]
const newli = document.createElement('li')
newli.innerHTML = value
ul.appendChild(newli)
}
</script>
</body>
</html>