console
var dom = {
btn1: document.querySelector('#btn1'),
btn2: document.querySelector('#btn2')
}
function click1 (){
console.log('防抖提交')
}
function click2(){
console.log('节流提交')
}
function debounce(callback,delay){
let timer = null
return function(){
if(timer){
clearTimeout(timer)
}
timer = setTimeout(()=>{
callback.apply(this,arguments)
},delay)
}
}
function throttle(callback,delay){
let flag = true
return function(){
if(flag){
setTimeout(()=>{
callback.apply(this,arguments)
flag = true
},delay)
}
flag = false
}
}
function throttle1(callback,delay){
let curTime = Date.now()
return function(){
let nowTime = Date.now()
if(nowTime - curTime >= delay){
curTime = Date.now()
return callback.apply(this,arguments)
}
}
}
btn1.addEventListener('click',debounce(click1,1000))
btn2.addEventListener('click',throttle1(click2,2000))
<html>
<title>
</title>
<body>
<button id='btn1' class="btn">
<span class="txt">防抖提交 </span>
</button>
<button id='btn2' class="btn">
<span class="txt"> 节流提交 </span>
</button>
</body>
</html>
.btn{
width: 100px;
height: 50px;
border-radius: 8px;
font-size: 15px;
}
#btn1{
color: yellow;
background-color: currentColor;
}
#btn2{
color: orangered;
background-color: currentColor;
}
.txt{
filter: grayscale(1) contrast(999) invert(1);
}