今天我们来写个简单的节流函数
500ms内点击多次只记录一次
效果如图:
图还没传上来
html和css部分:
<body>
每500毫秒可记录一次
<button id="btn">点我</button>
<div id="circle">0</div>
</body>
<style>
#circle {
width: 50px;
height: 50px;
border-radius: 50%;
background-color: rgb(199, 1, 1);
line-height: 50px;
text-align: center;
color: white;
opacity: 1.0;
transition: opacity .25s;
}
#circle.fade {
opacity: 0.0;
transition: opacity .25s;
}
</style>
Javascript部分:
function throttle(fn, time = 500){
let timer;
return function(...args){
if(timer == null){
fn.apply(this, args);
timer = setTimeout(() => {
timer = null;
}, time)
}
}
}
btn.onclick = throttle(function(e){
circle.innerHTML = parseInt(circle.innerHTML) + 1;
circle.className = 'fade';
setTimeout(() => circle.className = '', 250);
});
这个节流函数的实现比较简单,用高阶函数的思路,对原始函数进行包装, timer在500ms之后才会取消掉,也就是设置timer = null,如果不到500ms,timer不等于null就不会走到这个if函数里面去,就不会调用function,timer = null的时候,会先调用一次function。
下一篇来写一个防抖函数小案例。