console
function debounce(func, delay) {
let timer = null
return () => {
if(timer) clearTimeout(timer)
timer = setTimeout(() => {
func.apply(this, arguments)
}, delay)
}
}
function throttle(func, delay){
let timer = null
return () => {
if(!timer){
func.apply(this, arguments)
timer = setTimeout(() => {
timer = null
}, delay)
}
}
}
let buttonDoms = document.querySelectorAll('.button')
buttonDoms[0].addEventListener('click', debounce(testDebounce, 1000))
buttonDoms[1].addEventListener('click', throttle(testThrottle, 1000))
let resultDom = document.querySelector('.result-content')
function testDebounce() {
resultDom.innerHTML += '测试防抖<br/>'
}
function testThrottle() {
resultDom.innerHTML += '测试节流<br/>'
}
<div class="operate-box">
<div class="button">点击测试防抖</div>
<div class="button">点击测试节流</div>
</div>
<div class="result">
<div class="result-title">测试结果列表</div>
<div class="result-content"></div>
</div>
body{
padding: 50px;
}
.operate-box{
display: flex;
}
.button{
background: #2b2b2b;
color: #fff;
padding: 10px 20px;
border-radius: 10px;
cursor: pointer
}
.button:first-child{
margin-right: 30px;
}
.result{
margin-top: 50px;
font-size: 15px;
color:#fff;
padding: 10px 20px;
border: 2px solid #fff;
border-radius: 10px;
}
.result-title{
font-size: 18px;
font-weight: bold;
}
.result-content{
margin-top: 20px;
}